Python中异常处理
2018-01-05 10:14
363 查看
Python使用try...except...来处理异常,当Python遇到一个try语句,他会尝试执行try语句体内的语句,如果执行这些语句没有错误,控制转移到try...except...后面的语句,如果语句体内发生错误,python会寻找一个符合该错误的异常语句,然后执行处理代码。
try体内如果无异常产生,则执行else语句;
无论try体内无论是否有异常,finally语句都会执行,finally一般是无论是否异常发生都要执行清理的工作,比如打开后文件需要关闭文件的操作,连接网络后需要断开网络的操作。
我们的测试代码如下:
测试数据如下:
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 / number2 except 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) break finally: 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语句。
相关文章推荐
- Python异常处理
- python 异常处理
- Python爬虫入门——URLError异常处理
- Python 异常处理的实例详解
- python3 异常及异常处理
- Python引发异常,raise()及异常处理
- 【Python3之异常处理】
- python中的异常捕获处理机制(try...except...等语句)
- python---异常处理2
- 【Python之异常处理】
- python操作MYSQL实例及异常信息处理
- (Python)异常处理try...except、raise
- python简单执行异常处理
- python异常处理
- python 点滴记录12:异常处理
- Python异常处理体系
- Python 3(8)异常处理
- Python的异常处理机制 -- (转)
- [Python]网络爬虫(三):异常的处理和HTTP状态码的分类
- python的异常处理