[Python3] 033 異常


異常

1. 簡介

  • 廣義上的錯誤分為錯誤異常
  • 一個人不可能永遠是對的,但錯誤是可以避免或改正的
  • 異常是指在語法邏輯正確的前提下,出現的問題
  • Python 里,異常是一個類,可以處理和使用

2. 異常的分類

異常名 釋義
AssertError 斷言語句(assert)失敗
AttributeError 嘗試訪問未知的對象屬性
EOFError 用戶輸入文件末尾標志 EOF(Ctrl+d)
FloatingPointError 浮點計算錯誤
GeneratorExit generator.close() 方法被調用的時候
ImportError 導入模塊失敗的時候
IndexError 索引超出序列的范圍
KeyError 字典中查找一個不存在的關鍵字
KeyboardInterrupt 用戶輸入中斷鍵 (Ctrl+c)
MemoryError 內存溢出(可通過刪除對象釋放內存)
NameError 嘗試訪問一個不存在的變量
NotImplementedError 尚未實現的方法
OSError 操作系統產生的異常(例如打開一個不存在的文件)
OverflowError 數值運算超出最大限制
ReferenceError 弱引用 (weak reference) 試圖訪問一個已經被垃圾回收機制回收了的對象
RuntimeError 一般的運行時錯誤
StopIteration 迭代器沒有更多的值
SyntaxError Python 的語法錯誤
IndentationError 縮進錯誤
TabError Tab 和空格混合使用
SystemError Python 編譯器系統錯誤
SystemExit Python 編譯器進程被關閉
TypeError 不同類型間的無效操作
UnboundLocalError 訪問一個未初始化的本地變量(NameError 的子類)
UnicodeError Unicode 相關的錯誤(ValueError 的子類)
UnicodeEncodeError Unicode 編碼時的錯誤(UnicodeError 的子類)
UnicodeDecodeError Unicode 解碼時的錯誤(UnicodeError 的子類)
UnicodeTranslateError Unicode 轉換時的錯誤(UnicodeError 的子類)
ValueError 傳入無效的參數
ZeroDivisionError 除數為零

3. 出現異常小例子

例子

>>> num = int(input("Please enter a number: "))
Please enter a number: 0
>>> 100 / num
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 

4. 異常處理

  • 使得程序在最壞的情況下也能被妥善處理
  • Python 的異常處理模塊全部語法如下:
try:
    嘗試實現某個操作,
    如果沒出現異常,任務就可以完成
    如果出現異常,將異常從當前代碼塊扔出去嘗試解決異常
    (個人覺得,這里有點像 switch-case)
except 異常類型1:
    解決方案1:用於嘗試在此處處理異常解決問題
except 異常類型2:
    解決方案2:用於嘗試在此處處理異常解決問題
except (異常類型1, 異常類型2, ...):
    解決方案:針對多個異常使用相同的處理方式
excpet:
    解決方案:所有異常的解決方案
else:
    如果沒有出現任何異常,將會執行此處代碼
finally:
    管你有沒有異常都要執行的代碼
  • 流程
  1. 執行 try 下面的語句
  2. 如果出現異常,則在 except 語句里查找對應異常病進行處理
  3. 如果沒有出現異常,則執行 else 語句內容
  4. 最后,不管是否出現異常,都要執行 finally 語句
  • 除 except (最少一個)以外,else 和 finally 可選

5. 解決異常小例子

5.1 例子1

try:
    divisor = int(input("Plz input the divisor: "))
    rst = 100 / divisor
    print(f">>> rst = {rst}")
except:
    print("Illegal input! Please try again!")
    # exit()

>>>

$ python .\try-except_01.py
Plz input the divisor: 0
Illegal input! Please try again!

5.2 例子2

try:
    divisor = int(input("Plz input the divisor: "))
    rst = 100 / divisor
    print(f">>> rst = {rst}")
except ZeroDivisionError as e:
    print("Illegal input! The reasons for the error are: ")
    print(e)

>>>

$ python .\try-except_02.py
Plz input the divisor: 0
Illegal input! The reasons for the error are:
division by zero

5.3 例子3

try:
    divisor = int(input("Plz input the divisor: "))
    rst = 100 / divisor
    print(f">>> rst = {rst}")
except ZeroDivisionError as e:
    print("ZeroDivisionError!")
    print(e)
except NameError as e:
    print("NameError!")
    print(e)
except Exception as e:
    print("The reasons for the error are: ")
    print(e)
except ValueError as e:
    print("This sentence will not be executed!")

>>>

$ python .\try-except_03.py
Plz input the divisor: abc
The reasons for the error are:
invalid literal for int() with base 10: 'abc'

5.4 例子4

try:
    print("No Error.")
except NameError:
    print("NameError!")
else:
    print("Any Error?")

>>>

$ python .\try-except_04.py
No Error.
Any Error?

6. 手動引發異常

6.1 例子5

try:
    print("Let me throw an exception!")
    raise ValueError
    print("You can't see me.")
except NameError:
    print("NameError!")
except ValueError:
    print("ValueError!")
except Exception as e:
    print("The reasons for the error are: ")
    print(e)
finally:
    print("This sentence will certainly be carried out!")

>>>

$ python .\try-except_05.py
Let me throw an exception!
ValueError!
This sentence will certainly be carried out!

6.2 例子6

  • 自定義異常
class MyValueError(ValueError):
    pass


try:
    print("Let me throw an exception!")
    raise MyValueError
    print("You can't see me.")
except NameError:
    print("NameError!")
except ValueError:
    print("ValueError!")
except Exception as e:
    print("The reasons for the error are: ")
    print(e)
finally:
    print("This sentence will certainly be carried out!")

>>>

$ python .\try-except_06.py
Let me throw an exception!
ValueError!
This sentence will certainly be carried out!

7. 自定義異常

  • 只要是 raise 異常,就推薦自定義異常
  • 在自定義異常的時候,一般包含以下內容:
    • 自定義發生異常的異常代碼
    • 自定義發生異常后的問題提示
    • 自定義發生異常的行數
  • 最終的目的是,一旦發生異常,方便程序員快速定位錯誤現場

例子

In [1]: pritn()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-b44a7e815a2a> in <module>()
----> 1 pritn()

NameError: name 'pritn' is not defined

8. 利用異常解題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM