1. 程式人生 > >python try異常處理

python try異常處理

## 什麼是異常 python異常捕獲,在剛開始學的時候,經常會遇到兩種報錯資訊:語法錯誤和執行的異常。 語法錯誤在執行的時候就會報錯,同時控制端會告訴你錯誤所在的行; 但即便python程式語法是正確的,在執行它的時候,也有可能發生錯誤。比如請求的介面返回空,沒有做判斷直接拿這個變數進行下一步邏輯處理,就會出現程式碼異常。 大多數的異常都不會被程式處理,都以錯誤資訊的形式展現在這裡: ```python >>> 10 * (1/0) # 0 不能作為除數,觸發異常 Traceback (most recent call last): File "", line 1, in ? ZeroDivisionError: division by zero >>> 4 + spam*3 # spam 未定義,觸發異常 Traceback (most recent call last): File "", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 # int 不能與 str 相加,觸發異常 Traceback (most recent call last): File "", line 1, in 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 語句。 ```python try: num = int(input("Please enter a number: ")) print(num) except: print("You have not entered a number, please try again!") ``` ```python 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 程式碼塊沒有發生任何異常的時候被執行。 ```python 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() ``` ```python 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 程式碼。 ```python 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") ``` ```python PS D:\learning\git\work> python test.py The content was written to the file successfully test ``` ### raise 使用 raise 丟擲一個指定的異常 ```python def numb( num ): if num < 1: raise Exception("Invalid level!") # 觸發異常後,後面的程式碼就不會再執行 try: numb(0) # 觸發異常 except Exception as err: print(1,err) else: print(2) ``` ```python PS D:\learning\git\work> python test.py 1 Invalid level! PS D:\learning\git\work> ``` 語句中 Exception 是異常的型別(例如,NameError)引數標準異常中任一種,args 是自已提供的異常引數。 最後一個引數是可選的(在實踐中很少使用),如果存在,是跟蹤異常物件。 * 參考連結: https://www.runoob.com/python3/python3-errors-execptions.html https://www.runoob.com/python/python-exceptions.html ---- 鋼鐵 [email protected] 02