python try異常處理

什麼是異常

python異常捕獲,在剛開始學的時候,經常會遇到兩種報錯信息:語法錯誤和執行的異常。

語法錯誤在執行的時候就會報錯,同時控制端會告訴你錯誤所在的行;
但即便python程序語法是正確的,在運行它的時候,也有可能發生錯誤。比如請求的接口返回空,沒有做判斷直接拿這個變量進行下一步邏輯處理,就會出現代碼異常。

大多數的異常都不會被程序處理,都以錯誤信息的形式展現在這裡:

>>> 10 * (1/0)             # 0 不能作為除數,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero

>>> 4 + spam*3             # spam 未定義,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined

>>> '2' + 2               # int 不能與 str 相加,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

異常以不同的類型出現,這些類型都作為信息的一部分打印出來。例子中的類型有 ZeroDivisionError,NameError 和 TypeError。

常用標準異常類

異常名稱 描述
BaseException 所有異常的基類
SystemExit 解釋器請求退出
KeyboardInterrupt 用戶中斷執行(通常是輸入^C)
Exception 常規錯誤的基類
StopIteration 迭代器沒有更多的值
GeneratorExit 生成器(generator)發生異常來通知退出
StandardError 所有的內建標準異常的基類
ArithmeticError 所有數值計算錯誤的基類
FloatingPointError 浮點計算錯誤
OverflowError 數值運算超出最大限制
ZeroDivisionError 除(或取模)零 (所有數據類型)
AssertionError 斷言語句失敗
AttributeError 對象沒有這個屬性
EOFError 沒有內建輸入,到達EOF 標記
EnvironmentError 操作系統錯誤的基類
IOError 輸入/輸出操作失敗
OSError 操作系統錯誤
WindowsError 系統調用失敗
ImportError 導入模塊/對象失敗
LookupError 無效數據查詢的基類
IndexError 序列中沒有此索引(index)
KeyError 映射中沒有這個鍵
MemoryError 內存溢出錯誤(對於Python 解釋器不是致命的)
NameError 未聲明/初始化對象 (沒有屬性)
UnboundLocalError 訪問未初始化的本地變量
ReferenceError 弱引用(Weak reference)試圖訪問已經垃圾回收了的對象
RuntimeError 一般的運行時錯誤
NotImplementedError 尚未實現的方法
SyntaxError Python 語法錯誤
IndentationError 縮進錯誤
TabError Tab 和空格混用
SystemError 一般的解釋器系統錯誤
TypeError 對類型無效的操作
ValueError 傳入無效的參數
UnicodeError Unicode 相關的錯誤
UnicodeDecodeError Unicode 解碼時的錯誤
UnicodeEncodeError Unicode 編碼時錯誤
UnicodeTranslateError Unicode 轉換時錯誤
Warning 警告的基類
DeprecationWarning 關於被棄用的特徵的警告
FutureWarning 關於構造將來語義會有改變的警告
OverflowWarning 舊的關於自動提升為長整型(long)的警告
PendingDeprecationWarning 關於特性將會被廢棄的警告
RuntimeWarning 可疑的運行時行為(runtime behavior)的警告
SyntaxWarning 可疑的語法的警告
UserWarning 用戶代碼生成的警告

使用案例

try/except

異常捕捉可以使用 try/except 語句。

try:
    num = int(input("Please enter a number: "))
    print(num)
except:
    print("You have not entered a number, please try again!")

PS D:\learning\git\work> python test.py
Please enter a number: 60
60
PS D:\learning\git\work> python test.py
Please enter a number: d
You have not entered a number, please try again!
PS D:\learning\git\work>

try 語句執行順序如下:

  • 首先,執行 try 代碼塊。
  • 如果沒有異常發生,忽略 except 代碼塊,try 代碼塊執行後結束。
  • 如果在執行 try 的過程中發生了異常,那麼 try 子句餘下的部分將被忽略。
  • 如果異常的類型和 except 之後的名稱相符,那麼對應的 except 子句將被執行。
  • 一個 try 語句可能包含多個except子句,分別來處理不同的特定的異常。

try/except…else

如果使用這個子句,那麼必須放在所有的 except 子句之後。
else 子句將在 try 代碼塊沒有發生任何異常的時候被執行。

try:
    test_file = open("testfile.txt", "w")
    test_file.write("This is a test file!!!")
except IOError:
    print("Error: File not found or read failed")
else:
    print("The content was written to the file successfully")
    test_file.close()
PS D:\learning\git\work> python test.py
The content was written to the file successfully
PS D:\learning\git\work>
  • 如果寫入沒有問題,就會走到 else 提示成功。

try-finally

無論是否異常,都會執行最後 finally 代碼。

try:
    test_file = open("testfile.txt", "w")
    test_file.write("This is a test file!!!")
except IOError:
    print("Error: File not found or read failed")
else:
    print("The content was written to the file successfully")
    test_file.close()
finally:
    print("test")
PS D:\learning\git\work> python test.py
The content was written to the file successfully
test

raise

使用 raise 拋出一個指定的異常

def numb( num ):
    if num < 1:
        raise Exception("Invalid level!")
        # 觸發異常後,後面的代碼就不會再執行
try:
    numb(0)            # 觸發異常
except Exception as err:
    print(1,err)
else:
    print(2)
PS D:\learning\git\work> python test.py
1 Invalid level!
PS D:\learning\git\work>

語句中 Exception 是異常的類型(例如,NameError)參數標準異常中任一種,args 是自已提供的異常參數。
最後一個參數是可選的(在實踐中很少使用),如果存在,是跟蹤異常對象。

—- 鋼鐵 [email protected] 02.08.2021