1. 程式人生 > >Python學習-第八章 異常

Python學習-第八章 異常

異常

Python使用異常物件來表示異常狀態,並在遇到錯誤時引發異常。異常物件未被處理(或捕獲)時,程式將終止並顯示一條錯誤訊息。

類名 描述
Exception 幾乎所有的異常類都是從它派生而來的
AttributeError 引用屬性或給它賦值失敗時引發
OSError 作業系統不能執行指定的任務(如開啟檔案)時引發,有多個子類
keyError 使用對映中不存在的鍵時引發,為LookupError的子類
IndexError 使用序列中不存在的索引時引發,為LookupError的子類
NameError 找不到名稱(變數)時引發
SyntaxError 程式碼不正確時引發
TypeError 將內建操作或函式用於型別不正確的物件時引發
ValueError 將內建操作或函式用於這樣的物件時引發:其型別正確但不包含的值不合適
ZeroDivisionError 在除法或求模運算的第二個引數為零時引發

異常捕獲示例:

>>> try:
...    x=int(input('Enter the first number:'))
...    y=int(input('Enter the second number:'))
...    print(x/y)
... except ZeroDivisionError:
...    print("The second number can't be zero!")
...
Enter the first number:1
Enter the second number:0
The second number can't be zero!

捕獲異常後,如果要重新引發它(即繼續向上傳播),可呼叫raise且不提供任何引數(也可以顯式地提供捕獲的異常)
發生除零行為時,如果啟用了“抑制”功能,方法calc將(隱式地)返回None。換而言之,如果啟用了“抑制”功能,就不應依賴返回值。

>>> class MuffledCalculator:
...    muffled=False
...    def calc(self,expr):
...       try:
...          return eval(expr)
...       except ZeroDivisionError:
...          if self.muffled:
...             print('Division by zero is illegal')
...          else:
...              raise
...
>>> calculator=MuffledCalculator()
>>> calculator.calc('10/2')
5.0
>>> calculator.calc('10/0')     #關閉了抑制功能
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in calc
  File "<string>", line 1, in <module>
ZeroDivisionError: division by zero
>>> calculator.muffled=True
>>> calculator.calc('10/0')
Division by zero is illegal

可以給try/except語句新增一個else子句,當代碼段沒有引發異常時,才會跳出迴圈。

>>> while True:
...    try:
...       x=int(input('Enter the first number:'))
...       y=int(input('Enter the second number:'))
...       value=x/y
...       print('x/y is',value)
...    except:
...       print('Invalid input.Please try again.')
...    else:
...       break
...
Enter the first number:1
Enter the second number:0
Invalid input.Please try again.
Enter the first number:'foo'
Invalid input.Please try again.
Enter the first number:baz
Invalid input.Please try again.
Enter the first number:10
Enter the second number:2
x/y is 5.0

當try/except中用到finally是為了發生異常時執行清理工作。不管try子句中發生什麼異常,都將執行finally子句。

>>> x=None
>>> try:
...     x=1/0
... finally:
...     print('Cleaning up...')
...     del x
...
Cleaning up...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

如果只想發出警告,可使用模組warning中的函式warn
如果其他程式碼在使用你的模組,可使用模組warning時 中的函式filterwarnings來抑制你發出的警告

>>> from warnings import filterwarnings
>>> filterwarnings("error")
>>> warn("This function is really old...",DeprecationWarning)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
DeprecationWarning: This function is really old...
>>> filterwarnings("ignore",category=DeprecationWarning)
>>> warn("Another deprecation warning.",DeprecationWarning)
>>> warn("Something else.")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UserWarning: Something else.