python学习之异常处理

来源:互联网 发布:安卓服务端数据库 编辑:程序博客网 时间:2024/05/01 17:00

作为初学者,对于异常情况的处理,常常使用的方法是增加额外代码和逻辑。如使用多层if/else语句进行判断。这样虽然仅用初学者所学的基本知识即足够,但缺点是随着代码量的增加,开发者需要考虑的错误也就越来越多,复杂性随之增加,直到最后可能掩盖程序本来的目的。

而异常处理则不存在这个问题,可以一目了然地看出程序的主要作用,而不必操心可能哪里出问题,并编写额外的代码来避免运行时错误

以下为用Python语言对异常处理简单应用:

1,用增加代码和逻辑的方法:

if os.path.exists('spokers.txt')data = open('spokers.txt')for each_line in data:if not each_line.find(':') == -1:(role, line_spoken) = each_line.split(':', 1)print(role, end='')print(' said: ', end='')print(line_spoken, end='')data.close()else:print('The data file is missing!')

2,用使用异常处理(try/except)的方法

try:data = open(‘spokers.txt’)for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)print(role, end='')print(' said: ', end='')print(line_splken, end='')except:passdata.close()except:print('The data file is missing!')


3,指定特定异常

try:data = open(‘spokers.txt’)for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)print(role, end='')print(' said: ', end='')print(line_splken, end='')except ValueError:passdata.close()except IOError:print('The data file is missing!')

简而言之,使用try/except可以使我们关注代码真正要做的工作,减少不必要的代码和逻辑。

0 0
原创粉丝点击