第3章 處理異常

代碼有問題時,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





恢復代碼 
相關文章
相關標籤/搜索