try: print(10/0) except NameError as e: print(type(e)) print(e) except ZeroDivisionError as e: print(type(e)) print(e)
print('-------------End of the process-------------')
结果
1 2 3 4 5
<class'ZeroDivisionError'> division by zero -------------End of the process-------------
Process finished with exit code 0
10/0 , ZeroDivisionError 的异常被成功 catch
example 2 - 合并两个 except
从上面的例子可以看到,我们的程序对于两个不同异常的处理手段是一样的,那么可以合并
1 2 3 4 5 6 7
try: print(10/0) except (NameError, ZeroDivisionError) as e: print(type(e)) print(e)
print('-------------End of the process-------------')
1 2 3 4 5
<class'ZeroDivisionError'> division by zero -------------End of the process-------------
Process finished with exit code 0
依然成功执行了
example 3 - Exception
1 2 3 4 5 6 7 8 9
try: print('2'+2) except (NameError, ZeroDivisionError) as e: print(type(e)) print(e) except Exception as e: print(type(e)) print(e) print('-------------End of the process-------------')
1 2 3 4 5
<class'TypeError'> can only concatenate str (not"int") to str -------------End of the process-------------
try: a = 1+1 except (NameError, ZeroDivisionError) as e: print(type(e)) print(e) except Exception as e: print(type(e)) print(e) else: print('else') print('-------------End of the process-------------')
1 2 3 4
else -------------End of the process-------------
Process finished with exit code 0
语句中没有任何错误,所以程序执行else语句
当任一一个错误被捕获,else语句都不会被执行
example 5 - finally
1 2 3 4 5 6 7 8 9 10 11 12 13
try: print(10/0) except (NameError, ZeroDivisionError) as e: print(type(e)) print(e) except Exception as e: print(type(e)) print(e) else: print('else') finally: print('finally') print('-------------End of the process-------------')
1 2 3 4 5 6
<class'ZeroDivisionError'> division by zero finally -------------End of the process-------------
Reprint policy:
All articles in this blog are used except for special statements
CC BY 4.0
reprint policy. If reproduced, please indicate source
Liang Junyi
!