python異常處理機制和java類似,采用try-except-finally的結構.
try-except檢測異常
格式
try:
try_statement
except (ErrorType1, ErrorType2),e:
handle_statement
finally:
finally_statement
實例
#!/usr/bin/python
try:
a=12
b=0
c = a/b
except Exception, e:
print "Exception occurs: " , e
finally:
print "finally handle!"
上下文管理器(with…as…語句)with語句可以特別適用于首先打開資源最后釋放資源的場景,因為它會自動釋放占有的資源,不需要顯示地釋放資源
格式
with context_expr [as var]:
with_statement
raise引發異常格式
raise Exception[, args] or raise Exception(args)
實例
raise Exception(‘exampleException')
斷言檢測程序的關鍵點,斷言不成功的時候觸發AssertError(斷言錯誤)
格式如下
assert expression[, arguements]