Python 的錯誤和異常處理

2021-09-07 11:25:28 字數 1615 閱讀 4416

python 的語法錯誤或者稱之為解析錯,如下:

>>> while true print('

hello world')

file

"", line 1, in

?

while true print('

hello world')

^syntaxerror: invalid syntax

在此例中,函式 print() 被檢查到有錯誤,是它前面缺少了乙個冒號(:)。

語法分析器指出了出錯的一行,並且在最先找到的錯誤的位置標記了乙個小小的箭頭。

即便python程式的語法是正確的,在執行它的時候,也有可能發生錯誤。執行期檢測到的錯誤被稱為異常。

異常以不同的型別出現,這些型別都作為資訊的一部分列印出來:下面的例子中的型別有 zerodivisionerror,nameerror 和 typeerror。

大多數的異常都不會被程式處理,都以錯誤資訊的形式展現在這裡:

>>> 10 * (1/0)

traceback (most recent call last):

file

"", line 1, in

?zerodivisionerror: division by zero

>>> 4 + spam*3traceback (most recent call last):

file

"", line 1, in

?nameerror: name

'spam'is

notdefined

>>> '

2' + 2traceback (most recent call last):

file

"", line 1, in

?typeerror: can

't convert

'int'

object to str implicitly

以下例子中,讓使用者輸入乙個合法的整數,但是允許使用者中斷這個程式(使用 control-c 或者作業系統提供的方法)。使用者中斷的資訊會引發乙個 keyboardinterrupt 異常。

>>> while

true:

try:

x = int(input("

please enter a number: "))

break

except

valueerror:

print("

oops! that was no valid number. try again ")

try語句按照如下方式工作;

python 使用 raise 語句丟擲乙個指定的異常。例如:

>>> raise nameerror('

hithere')

traceback (most recent call last):

file

"", line 1, in

?nameerror: hithere

raise 唯一的乙個引數指定了要被丟擲的異常。它必須是乙個異常的例項或者是異常的類(也就是 exception 的子類)。

python 基礎篇 錯誤和異常處理

所謂語法錯誤,也就是你寫的 不符合程式設計規範,無法被識別與執行,比如下面這個例子 if name is not none print name if 語句漏掉了冒號,不符合 python 的語法規範,所以程式就會報錯invalid syntax。異常則是指程式的語法正確,也可以被執行,但在執行過程...

python基礎之錯誤和異常處理

import exception exce 在捕獲錯誤異常的時候 是要根據具體的錯誤型別來捕獲的 用乙個塊 可以捕獲多個不同型別的異常 exception 可以捕獲所有異常 當對出現的問題或者錯誤不確定的情況下 可以使用此種 print dir exception try print b 捕獲邏輯的...

python 錯誤異常的簡單處理

常見錯誤型別 indentationerror 縮排錯誤 valueerror 值錯誤 try 語句 語句無異常則執行語句,語句有異常執行except except 異常名 print 異常說明 try 執行 塊1 except 塊1異常執行 else 塊1無異常執行 finally 不論是否異常都...