Python3 #錯誤和異常

做爲Python初學者,在剛學習Python編程時,常常會看到一些報錯信息,在前面咱們沒有說起,這章節咱們會專門介紹。python

Python有兩種錯誤很容易辨認:語法錯誤和異常編程

語法錯誤

Python 的語法錯誤或者稱之爲解析錯,是初學者常常碰到的,以下實例函數

lcassmates = ['Maichesal','asdas','Treas']
異常錯誤以下
Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'lcassmatas' is not defined
正確寫法
>>> lcassmates = ['Maichesal','asdas','Treas'];
>>> lcassmates
['Maichesal', 'asdas', 'Treas']

這個例子中,函數 lcassmates 被檢查到有錯誤,是它句尾缺乏了一個結束分號(;)。學習

異常

即使Python程序的語法是正確的,在運行它的時候,也有可能發生錯誤。運行期檢測到的錯誤被稱爲異常。spa

大多數的異常都不會被程序處理,都以錯誤信息的形式展示在這裏:操作系統

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: Can't convert 'int' object to str implicitly

異常以不一樣的類型出現,這些類型都做爲信息的一部分打印出來: 例子中的類型有 ZeroDivisionError,NameError 和 TypeError。code

異常處理

如下例子中,讓用戶輸入一個合法的整數,可是容許用戶中斷這個程序(使用 Control-C 或者操做系統提供的方法)。用戶中斷的信息會引起一個 KeyboardInterrupt 異常。ci

錯誤信息的前面部分顯示了異常發生的上下文,並以調用棧的形式顯示具體信息。input

>> while True:
        try:
            x = int(input("Please enter a number: "))
            break
        except ValueError:
            print("Oops!  That was no valid number.  Try again   ")

try語句按照以下方式工做;it

  • 首先,執行try子句(在關鍵字try和關鍵字except之間的語句)
  • 若是沒有異常發生,忽略except子句,try子句執行後結束。
  • 若是在執行try子句的過程當中發生了異常,那麼try子句餘下的部分將被忽略。若是異常的類型和 except 以後的名稱相符,那麼對應的except子句將被執行。最後執行 try 語句以後的代碼。
  • 若是一個異常沒有與任何的except匹配,那麼這個異常將會傳遞給上層的try中。
相關文章
相關標籤/搜索