Lesson 027 —— python 錯誤和異常
Lesson 027 —— python 錯誤和異常
Python有兩種錯誤很容易辨認:語法錯誤和異常。
語法錯誤
Python 的語法錯誤或者稱之為解析錯,是初學者經常碰到的,如下例項
>>>while True print('Hello world')
File "<stdin>", line 1, in ?
while True print('Hello world')
^
SyntaxError: invalid syntax
這個例子中,函式 print() 被檢查到有錯誤,是它前面缺少了一個冒號(:)。
語法分析器指出了出錯的一行,並且在最先找到的錯誤的位置標記了一個小小的箭頭。
異常
即便Python程式的語法是正確的,在執行它的時候,也有可能發生錯誤。執行期檢測到的錯誤被稱為異常。
大多數的異常都不會被程式處理,都以錯誤資訊的形式展現在這裡:
>>>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。
錯誤資訊的前面部分顯示了異常發生的上下文,並以呼叫棧的形式顯示具體資訊。
異常處理
以下例子中,讓使用者輸入一個合法的整數,但是允許使用者中斷這個程式(使用 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語句按照如下方式工作:
- 首先,執行try子句(在關鍵字try和關鍵字except之間的語句)
- 如果沒有異常發生,忽略except子句,try子句執行後結束。
- 如果在執行try子句的過程中發生了異常,那麼try子句餘下的部分將被忽略。如果異常的型別和 except 之後的名稱相符,那麼對應的except子句將被執行。最後執行 try 語句之後的程式碼。
- 如果一個異常沒有與任何的except匹配,那麼這個異常將會傳遞給上層的 try 中。
一個 try 語句可能包含多個except子句,分別來處理不同的特定的異常。最多隻有一個分支會被執行。
處理程式將只針對對應的try子句中的異常進行處理,而不是其他的 try 的處理程式中的異常。
一個except子句可以同時處理多個異常,這些異常將被放在一個括號裡成為一個元組,例如:
except (RuntimeError, TypeError, NameError):
pass
最後一個except子句可以忽略異常的名稱,它將被當作萬用字元使用。你可以使用這種方法列印一個錯誤資訊,然後再次把異常丟擲。
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
try except 語句還有一個可選的else子句,如果使用這個子句,那麼必須放在所有的except子句之後。這個子句將在** try 子句沒有發生任何異常的時候執行**。例如:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
使用 else 子句比把所有的語句都放在 try 子句裡面要好,這樣可以避免一些意想不到的、而except又沒有捕獲的異常。
異常處理並不僅僅處理那些直接發生在try子句中的異常,而且還能處理子句中呼叫的函式(甚至間接呼叫的函式)裡丟擲的異常。例如:
>>>def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:', err)
Handling run-time error: int division or modulo by zero
丟擲異常
Python 使用 raise 語句丟擲一個指定的異常。例如:
>>>raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
raise 唯一的一個引數指定了要被丟擲的異常。它必須是一個異常的例項或者是異常的類(也就是 Exception 的子類)。
如果你只想知道這是否丟擲了一個異常,並不想去處理它,那麼一個簡單的 raise 語句就可以再次把它丟擲。
>>>try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
使用者自定義異常
你可以通過建立一個新的異常類來擁有自己的異常。異常類繼承自 Exception 類,可以直接繼承,或者間接繼承,例如:
>>>class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
>>> try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'
在這個例子中,類 Exception 預設的 __init__()
被覆蓋。
當建立一個模組有可能丟擲多種不同的異常時,一種通常的做法是為這個包建立一個基礎異常類,然後基於這個基礎類為不同的錯誤情況建立不同的子類:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
大多數的異常的名字都以"Error"結尾,就跟標準的異常命名一樣。
定義清理行為
try 語句還有另外一個可選的子句,它定義了無論在任何情況下都會執行的清理行為。 例如:
>>>try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
以上例子不管 try 子句裡面有沒有發生異常,finally 子句都會執行。
如果一個異常在 try 子句裡(或者在 except 和 else 子句裡)被丟擲,而又沒有任何的 except 把它截住,那麼這個異常會在 finally 子句執行後再次被丟擲。
下面是一個更加複雜的例子(在同一個 try 語句裡包含 except 和 finally 子句):
>>>def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
預定義的清理行為
一些物件定義了標準的清理行為,無論系統是否成功的使用了它,一旦不需要它了,那麼這個標準的清理行為就會執行。
這面這個例子展示了嘗試開啟一個檔案,然後把內容列印到螢幕上:
for line in open("myfile.txt"):
print(line, end="")
以上這段程式碼的問題是,當執行完畢後,檔案會保持開啟狀態,並沒有被關閉。
關鍵詞 with 語句就可以保證諸如檔案之類的物件在使用完之後一定會正確的執行他的清理方法:
with open("myfile.txt") as f:
for line in f:
print(line, end="")
以上這段程式碼執行完畢後,就算在處理過程中出問題了,檔案 f 總是會關閉。