程式在運行時總是會發生一些錯誤,在python中的錯誤大致分為兩類:語法錯誤和異常(例外)
語法錯誤的錯誤訊息為SyntaxError,python直譯器會在語法錯誤那行顯示一個箭頭,例如下面的範例在print()函式找到了錯誤,在print()函式之前應該要有一個冒號 ":"
while True print('Hello world')
File "", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
有時候在程式中即使語法正確但在執行時還是有可能發生錯誤,我們稱為異常(例外),例如下列範例中的錯誤訊息ZeroDivisionError、NameError、TypeError,分別代表除法分母為零錯誤、變數名稱錯誤、型別錯誤
>>> 10 * (1/0) #除法錯誤,分母為零
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3 #變數名稱錯誤,變數name還未定義
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2 #型別錯誤,string及int之間不提供加法運算
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
寫程式最重要的能力之一是要會看懂錯誤訊息(Error Message),才有辦法快速找出程式中的錯誤,官網文件中也提供了各種異常及它們代表的意義
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
python中處理異常的機制為使用try-except statement,用法為將有可能出現例外的程式碼放進try程式區塊,except程式區塊則是例外發生時的處理,關於例外處理相關的關鍵詞有:
關鍵詞 | 描述 |
---|---|
try | 放置可能有例外狀況的程式碼 |
except | 例外狀況處置 |
else | 當沒有發生例外狀況時執行 |
finally | 無論任何情況皆會執行 |
下列兩個例子分別展示有例外情況與沒有例外情況用法
# 例外發生情況
try:
print('Pass:', pass)
except:
print('except happened!')
else:
print('else happened!')
finally:
print('finally pass the 30 days challenge!')
# 沒有發生例外
passChallenge= True
try:
print('Pass:', passChallenge)
except:
print('except happened!')
else:
print('else happened!')
finally:
print('finally pass the 30 days challenge!')
Python - 錯誤與異常
https://docs.python.org/zh-cn/3/tutorial/errors.html
Python - 內建異常
https://docs.python.org/zh-cn/3/library/exceptions.html#bltin-exceptions