程序的錯誤
語法錯誤,邏輯錯誤和運行時錯誤
- 語法錯誤是指源代碼中的拼寫等錯誤,這些錯誤導致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~~