Python使用try...except...来处理异常,当Python遇到一个try语句,他会尝试执行try语句体内的语句,如果执行这些语句没有错误,控制转移到try...except...后面的语句,如果语句体内发生错误,python会寻找一个符合该错误的异常语句,然后执行处理代码。
try:<body>
except <ErrorType1>:<handler1>
except <ErrorType2>:<handler2>
else:<process_else>
finally:<process_finally>
try体内如果无异常产生,则执行else语句;
无论try体内无论是否有异常,finally语句都会执行,finally一般是无论是否异常发生都要执行清理的工作,比如打开后文件需要关闭文件的操作,连接网络后需要断开网络的操作。
我们的测试代码如下:
def main():while True:try:number1, number2 = eval(input('Enter two number,separated by a comma:'))result = number1 / number2except ZeroDivisionError:print('Division by zero!')except SyntaxError:print('A comma may be missing in the input')except:print('Something wrong in the input')else:print('No exception,the result is:', result)breakfinally:print('executing the final clause')
main()
测试数据如下:
Enter two number,separated by a comma:3,4
No exception,the result is: 0.75
executing the final clause
Enter two number,separated by a comma:2,0
Division by zero!
executing the final clause
Enter two number,separated by a comma:
当我们输入3,4时,代码运行正常,执行else和finally语句;当我们输入2,0 时,代码执行except
ZeroDivisionError和finally语句。我们可以看到无论try中是否错误发生,都会执行finally语句。