程式的錯誤
文法錯誤,邏輯錯誤和運作時錯誤
- 文法錯誤是指源代碼中的拼寫等錯誤,這些錯誤導緻python編譯器無法把python源代碼轉換為位元組碼,故也稱之為編譯錯誤。
- 邏輯錯誤是程式可以執行(程式運作本身不報錯)但執行結果不正确。對于邏輯錯誤,python解釋器無能為力,需要根據結果來調試判斷。
-
運作時錯誤是當:
1.程式中沒有導入相關的子產品(例如,import random)時,解釋器将在運作時抛出NameError錯誤資訊
2.程式中包括零除運算,解釋器将在運作時抛出ZeroDivisionError錯誤資訊
3.程式中試圖打開不存在的檔案,解釋器将在運作時抛出FileNotFoundError錯誤資訊
異常
異常指的是程式在沒有文法錯誤的前提下,在運作期間産生的特定錯誤
每個指定錯誤都對應一個異常類對象,當産生某個特定錯誤時,其對應的異常類對象的執行個體對象就會被抛出
如果在程式中對抛出的異常執行個體對象不進行捕獲和處理,程式就會停止運作,并且列印錯誤的詳細資訊,包括:
- Traceback,它指的是異常調用堆棧的跟蹤資訊,其中列出了程式中的相關行數。
- 對應的異常類對象的名稱,以及異常的錯誤資訊。
内置的異常類
所有内置異常類對象的基類是Exception
help(Exception)
>>>
>Help on class Exception in module builtins:
class Exception(BaseException)
| Common base class for all non-exit exceptions.
|
| Method resolution order:
| Exception
| BaseException
| object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from BaseException:
|
| __delattr__(self, name, /)
| Implement delattr(self, name).
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setattr__(self, name, value, /)
| Implement setattr(self, name, value).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
異常處理(try…except…else…finally結構)
try…except
try…except語句的文法格式:
try:
可能會産生異常的代碼
except 異常類對象1:
目前except子句處理異常的代碼
except 異常類對象2:
目前except子句處理異常的代碼
…
except 異常類對象n:
目前except子句處理異常的代碼
result = 1 / 0
print(result)
>>>
>---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-2a7c00a6da7f> in <module>()
----> 1 result = 1 / 0
2 print(result)
ZeroDivisionError: division by zero
try:
result = 1 / 0
print(result)
except ZeroDivisionError:
print("0不能作為除數!")
>>>
>0不能作為除數!
except後面的錯誤要注意類型
try:
result = 1 / 0
print(result)
except TypeError:#錯誤不對
print("0不能作為除數!")
>>>
>---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-4-4486f690affe> in <module>()
1 try:
----> 2 result = 1 / 0
3 print(result)
4 except TypeError:
5 print("0不能作為除數!")
ZeroDivisionError: division by zero
result = int('abc')
print(result)
>>>
>---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-960d03050136> in <module>()
----> 1 result = int('abc')
2 print(result)
ValueError: invalid literal for int() with base 10: 'abc'
try:
result = 1 / 0
print(result)
except ArithmeticError:#ArithmeticError為ZeroDivisionError父類
print("數學錯誤")
>>>
>數學錯誤
如果捕獲的異常之間有繼承關系,則結果跟其順序有關系
try:
result = 1 / 0
print(result)
except ArithmeticError:
print("數學錯誤")
except ZeroDivisionError:
print("0不能作為除數!")
>>>
>數學錯誤
try:
result = 1 / 0
print(result)
except ZeroDivisionError:
print("0不能作為除數!")
except ArithmeticError:
print("數學錯誤")
>>>
>0不能作為除數!
多種異常輸出一個結果可以合并
try:
result = 1 / 0
print(result)
except (TypeError,ZeroDivisionError,ValueError):
print("運作出錯了!")
>>>
>運作出錯了!
try:
result = 1 / 0
print(result)
except ZeroDivisionError as err:
print(type(err))
print(err)
>>>
><class 'ZeroDivisionError'>
division by zero
try…except…else…
try:
可能會産生異常的代碼
except 異常類對象1:
目前except子句處理異常的代碼
except 異常類對象2:
目前except子句處理異常的代碼
…
except 異常類對象n:
目前except子句處理異常的代碼
else:
try語句塊中沒有産生異常時執行的代碼
while True:
try:
x = int(input('請輸入一個整數:'))
except ValueError:
print('無效的輸入,請再次輸入')
else:
print('輸入的整數為:',x)
break
>>>
>請輸入一個整數:a
無效的輸入,請再次輸入
請輸入一個整數:b
無效的輸入,請再次輸入
請輸入一個整數:s
無效的輸入,請再次輸入
請輸入一個整數:6
輸入的整數為: 6
try…except…finally…
try:
可能會産生異常的代碼
except 異常類對象1:
目前except子句處理異常的代碼
except 異常類對象2:
目前except子句處理異常的代碼
…
except 異常類對象n:
目前except子句處理異常的代碼
finally:
總會被執行的代碼
- 通常在finally從句中釋放資源
- 若except沒有捕獲異常,則運作finally,則終止且抛出沒有被捕獲到的異常
raise(手動抛出異常執行個體對象)
raise 異常類對象[([參數])]
如果沒有傳入參數,可以省略掉小括号。
raise ZeroDivisionError('0不能作為除數')
>>>
>---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-14-5b1ed144e826> in <module>()
----> 1 raise ZeroDivisionError('0不能作為除數')
ZeroDivisionError: 0不能作為除數
raise ZeroDivisionError()#無參數時,小括号可以省略
>>>
>---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-15-10ba4d062a9d> in <module>()
----> 1 raise ZeroDivisionError()
ZeroDivisionError:
raise Warning("哔!")
>>>
>---------------------------------------------------------------------------
Warning Traceback (most recent call last)
<ipython-input-16-98ba533ebbb8> in <module>()
----> 1 raise Warning("哔!")
Warning: 哔!
自定義異常
class MyException(Exception):
pass
raise MyException('bibibibibi~~')
>>>
>---------------------------------------------------------------------------
MyException Traceback (most recent call last)
<ipython-input-5-f791c2df0850> in <module>()
1 class MyException(Exception):
2 pass
----> 3 raise MyException('bibibibibi~~')
MyException: bibibibibi~~