python基础之异常捕获

2021/4/16 14:55:15

本文主要是介绍python基础之异常捕获,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

当我们程序遇到异常时,会导致程序中止运行,见如下例子:

def test():
        a = int(input("please input:"))
        b = int(input("please input:"))
        result = a / b
        print(result)

def test_1():
    print("this is test_1")

test()
print("------")
test_1()

运行结果如下:

please input:a
Traceback (most recent call last):
  File "E:/practicemore/fff.py", line 15, in <module>
    test()
  File "E:/practicemore/fff.py", line 7, in test
    a = int(input("please input:"))
ValueError: invalid literal for int() with base 10: 'a'

从运行结果我们可以看出,当输入字母“a”时,程序就报错了。
这样的话,其后的语句均为被执行,即程序中断了。

为了让程序报错后能继续运行,并对已知可能报错的地方进行异常的捕获,我们会用到try...except语句:
1、try的代码模块中是可能会出错的代码。
2、except模块是对异常及类型的捕获。
我们对上面的程序进行一个异常捕获:

def test():
    try:
        a = int(input("please input:"))
        b = int(input("please input:"))
        result = a / b
        print(result)
    except:
        print("出现异常了,兄弟")

def test_1():
    print("this is test_1")

test()
print("------")
test_1()

执行结果如下:

please input:a
出现异常了,兄弟
------
this is test_1

我们可以看到,当我们同样输入了字母“a”后,虽然try模块中的后续语句未被执行,但是except何后续的打印及test_1都执行了。
重点:
1、except模块是try模块中报错后执行
2、except模块可以有多个,可以捕获具体的异常类型

try...except...finally
我们看一下如下例子:

def test():
    try:
        a = int(input("please input:"))
        b = int(input("please input:"))
        result = a / b
        print(result)
    except:
        print("出现异常了,兄弟")
    finally:
        print("this is finally")

def test_1():
    print("this is test_1")

当执行结果未报错时:

please input:3
please input:1
3.0
this is finally
------
this is test_1

我们可以看到,执行结果未报错时,finally模块被执行了
当执行结果报错时:

please input:3
please input:0
出现异常了,兄弟
this is finally
------
this is test_1

我们可以看到,执行结果报错时,finally模块也被执行了
总结:try...except...finally结构,无论报错与否,finally模块中的语句一定会被执行。

try...except...finally...else结构
看如下例子:

def test():
    try:
        a = int(input("please input:"))
        b = int(input("please input:"))
        result = a / b
        print(result)
    except:
        print("出现异常了,兄弟")
    else:
        print("this is else")
    finally:
        print("this is finally")


def test_1():
    print("this is test_1")

执行报错时:

please input:a
出现异常了,兄弟
this is finally
------
this is test_1

我们可以看到,报错时except和finally语句块被执行了
未报错时:

please input:3
please input:1
3.0
this is else
this is finally
------
this is test_1

我们可以看到,未报错时,else和finally语句块被执行了。
总结:
1、finally语句块一定是放在try...except...else...finally语句块结构的最后,else放在except后
2、当try语句块未报错时,不执行except,执行else和finally
3、当try语句块报错时,执行except和finally

tips:try后面可以不跟except,可以直接跟finally,而不能直接跟else



这篇关于python基础之异常捕获的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程