第3章 处理异常

2023-01-31 01:01:50 异常
代码有问题时,python会显示traceback,后面跟着一条错误信息。这个错误被称为异常(exception)。
 
格式
try:
可能产生运行时错误的代码
except:
错误恢复代码
测试文本
Man: Is this your car?
Other man: No.
Woman: What color is it?
Bye.
Go on
增加额外的代码处理错误
#!/usr/local/Python
with open('E:/python code/other/tmp/test.txt') as fd:
for each_line in fd:
if each_line.find(':') > 0:
(role, line_spoken) = each_line.split(':',1)
print(role),
print(' said '),
print(line_spoken),
使用try-except处理错误
#!/usr/local/python
import os,sys
try:
with open('E:/python code/other/tmp/test.txt') as fd:
for each_line in fd:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role),
print(' said '),
print(line_spoken),
except ValueError:
pass
except IOError:
print('The file is missing.')



错误




sfsdfsdfdsfsd




nisdfds ffdsdsfd





恢复代码 

相关文章