什么是例外
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 是自已提供的例外引數,
最后一個引數是可選的(在實踐中很少使用),如果存在,是跟蹤例外物件,
- 參考鏈接:
https://www.runoob.com/python3/python3-errors-execptions.html
https://www.runoob.com/python/python-exceptions.html
---- 鋼鐵 [email protected] 02.08.2021
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/257978.html
標籤:Python
上一篇:Mybatis入門簡介
