11、python中的try/except/else/finally语句

用实例来解释下Python中的try/except/else/finally语句的执行顺序


1、如果try中的语句块执行成功,则会先执行try,再执行else,再执行finally

a='abc'

try:
    print(a[0])
except IndexError as e:
    print('AAA')
except IOError as e:
    print('BBB')
else:
    print('CCC')
finally:
    print('DDD')
运行结果为:

C:\Python36\python.exe E:/python/test1/day5/try.py
a
CCC
DDD


2、如果try语句块未执行成功,出现异常,则从except中找对应的异常,能找到就打印,然后去执行finally

a='abc'

try:
    print(a[9])
except IOError as e:
    print('AAA')
except IndexError as e:
    print('BBB')
else:
    print('CCC')
finally:
    print('DDD')

上面a[9] 会导致IndexError,即try语句块报IndexError异常,那么去第一个except找对应的错误,第一个是IOError,不匹配,继续从下面的except找,第二个是IndexError,匹配,执行该语句块,打印‘BBB’,然后打印finally语句。

执行结果:

C:\Python36\python.exe E:/python/test1/day5/try.py
BBB
DDD


3、如果try语句块未执行成功,出现异常,则从except中找对应的异常,当在所有的except中都找不到匹配的异常,则会将异常抛出,然后去执行finally。(并不是匹配不到执行else)

a='abc'

try:
    print(a[9])
except IOError as e:
    print('AAA')
except ImportError as e:
    print('BBB')
else:
    print('CCC')
finally:
    print('DDD')
执行结果:

C:\Python36\python.exe E:/python/test1/day5/try.py
Traceback (most recent call last):
DDD
  File "E:/python/test1/day5/try.py", line 4, in <module>
    print(a[9])
IndexError: string index out of range


Process finished with exit code 1



4、如果我们想匹配不到异常则统一执行某个动作怎么办?使用except Exception as e语句

a='abc'

try:
    print(a[9])
except IOError as e:
    print('AAA')
except ImportError as e:
    print('BBB')
except Exception as e:
    print('EEE')
else:
    print('CCC')
finally:
    print('DDD')


执行结果:

C:\Python36\python.exe E:/python/test1/day5/try.py
EEE
DDD


Process finished with exit code 0

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页