第10章 异常
一、异常
1 检测和处理异常
(1)try-except语句
try:
try_suite #监控这里的异常
except Exception[, reason]:
except_suite #异常处理代码
(2)“带有多个except的try语句”和“处理多个异常的except语句”
(3)捕获所有异常
try:
:
except Exception, e:
# error occurred, log 'e', etc.
也可以用裸except语句(不推荐):
try:
try_suite;
except:
# error occurred, log 'e', etc.
(4)异常参数
(5)else子句和finally子句
(6)try-except-else-finally:厨房一锅端
try:
try_suite
except Exception1:
suite_for_Exception1
except (Exception2, Exception3, Exception4):
suite_for_Exceptions_2_3_and_4
except Exception5, Argument5:
suite_for_Exception5_plus_argument
except (Exception6, Exception7), Argument67:
suite_for_Exceptions6_and_7_plus_argument
except:
suite_for_all_other_exceptions
else:
no_exceptions_detected_suite
finally:
always_execute_suite
2 上下文管理
with语句:
with context_expr [as var]:
with_suite
举例:
with open('/etc/passwd', 'r') as f:
for eachLine in f:
# ...do stuff with eachLine or f...
注:无论的在这一段代码的开始,中间,还是结束时发生异常,会执行清理的代码,此外文件仍会被自动的关闭.
3 触发异常
raise [SomeException [, args [, traceback]]]
4 标准异常
二、断言
assert expression[, arguments]