如何在PYTHON里捕获和抛出异常

2025-12-29 14:20:06

1、result = int(input("What is the result when 1 plus 1?"))

#这里需要用户输入整数,但是这里却是字符,那么就显示出错。

如何在PYTHON里捕获和抛出异常

2、try:

    result = int(input("What is the result when 1 plus 1?"))

except:

    print("The value is wrong!")

except Exception as i:

    print("This is unknow error %s. " % i)

print("The end!")

#如果不知道还会有什么异常可以用Exception,但是这里出错是因为单独except要放在后面。

如何在PYTHON里捕获和抛出异常

3、try:

    result = int(input("What is the result when 1 plus 1?"))

except Exception as result:

    print("This is unknow error %s. " % result)

except:

    print("The value is wrong!")

print("The end!")

#这个时候就可以排除所有错误了。

如何在PYTHON里捕获和抛出异常

4、try:

    result = int(input("What is the result when 1 plus 1?"))

except Exception as result:

    print("This is unknow error %s. " % result)

else:

    print("No error!")

finally:

    print("The end!")

#可以在后面加上else,如果没有错误就会运行,形成try...else语句。

如何在PYTHON里捕获和抛出异常

5、try:

    result = int(input("What is the result when 1 plus 1?"))

except Exception as result:

    print("This is unknow error %s. " % result)

else:

    print("No error!")

finally:

    print("The end!")

#但是如果有异常else不会运行。但是finally是会运行的。

如何在PYTHON里捕获和抛出异常

6、def test1():

    return int(input("What is the result when 1 plus 1?"))

test1()

#这里可以看出发现异常系统没有马上终止,而是先进行传递。

如何在PYTHON里捕获和抛出异常

7、def test1():

    return int(input("What is the result when 1 plus 1?"))

try:

    test1()

except Exception as result:

    print("somthing is wrong %s. " % result)

    

#面对这种情况也是可以在最后面加上try和except来捕获异常。

如何在PYTHON里捕获和抛出异常

8、def test():

    result = int(input("What is the result when 1 plus 1?"))

    if result.isalpha():

        return result

    print("there is an error.")

    error = Exception("输入错误")

    raise error

    

test()

#我们可以主动捕获异常。

如何在PYTHON里捕获和抛出异常

9、def test():

    result = input("What is the result when 1 plus 1?")

    if len(result) == 1:

        return result

    print("there is an error.")

    error = Exception("输入错误")

    raise error

try:

    print(test())

except Exception as result:

    print(result)  

    

#设置try和except在下方,然后正常运行一下。

如何在PYTHON里捕获和抛出异常

10、def test():

    result = input("What is the result when 1 plus 1?")

    if len(result) == 1:

        return result

    else:

        print("there is an error.")

        raise Exception("输入错误")

try:

    print(test())

except Exception as result:

    print(result)  

#这个时候就可以在有错误的时候捕获到异常。先运行,有错误的话捕获异常,并且在except里面把异常当结果输出。

如何在PYTHON里捕获和抛出异常

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢