1.異常的處理
基本格式:
try:
嘗試行爲
except 異常種類:
異常處理方法
finally:
最終處理(無論是否異常都會執行,常用於資源的釋放)
演示示例:
>>> try:
... print(1/0)
... except Exception:
... print("執行錯誤")
... finally:
... print("最終執行")
...
執行錯誤
最終執行
>>>
>>> try:
... print(1/1)
... except Exception:
... print("執行錯誤")
... finally:
... print("最終執行")
...
1.0
最終執行
>>>
當存在多個異常選項時:
python會按照順序一個個比對是否屬於該類型,如果是則執行該段,後續異常不再比對。因此如果所寫的異常前後之間具有包含關係,python不會報警,但不建議將大異常寫在小異常之前。
>>> try:
... print(1/0)
... except ZeroDivisionError:
... print("執行錯誤02")
... except Exception:
... print("執行錯誤01")
... finally:
... print("最終執行")
...
執行錯誤02
最終執行
>>> try:
... print(1/0)
... except Exception:
... print("執行錯誤01")
... except ZeroDivisionError:
... print("執行錯誤02")
... finally:
... print("最終執行")
...
執行錯誤01
最終執行
注意事項:
①finally中的語句無論怎麼樣都會被執行;
②except可寫多個分別接收不同異常;
2.異常的拋出
基本格式:
raise 異常類型
演示實例:
>>> def throwEx():
... raise Exception
...
>>> throwEx()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in throwEx
Exception
3.自定義異常
基本格式:
①繼承已有異常類
②複寫__int__構造函數和__str__提示函數
演示示例:
>>> class ExceptionType(Exception):
... def __init__(self):
... pass
... def __str__(self):
... return "這是一個自定義異常"
...
>>> def throeEx():
... raise ExceptionType
...
>>> throeEx()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in throeEx
__main__.ExceptionType: 這是一個自定義異常