Python3 錯誤和異常、assert(斷言)、Traceback詳解


Python3 錯誤和異常

  作為 Python 初學者,在剛學習 Python 編程時,經常會看到一些報錯信息,在前面我們沒有提及,這章節我們會專門介紹。

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

Python assert(斷言)用於判斷一個表達式,在表達式條件為 false 的時候觸發異常。

語法錯誤

Python 的語法錯誤或者稱之為解析錯,是初學者經常碰到的,如下實例

>>> while True print('Hello world')
  File "<stdin>", line 1, in ?
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

這個例子中,函數 print() 被檢查到有錯誤,是它前面缺少了一個冒號 : 。

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

異常

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

大多數的異常都不會被程序處理,都以錯誤信息的形式展現在這里:

實例

>>> 10 * (1/0)             # 0 不能作為除數,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3             # spam 未定義,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2               # int 不能與 str 相加,觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

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

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

異常處理

try/except

異常捕捉可以使用 try/except 語句。

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

while True:
    try:
        x = int(input("請輸入一個數字: "))
        break
    except ValueError:
        print("您輸入的不是數字,請再次嘗試輸入!")

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

  • 首先,執行 try 子句(在關鍵字 try 和關鍵字 except 之間的語句)。

  • 如果沒有異常發生,忽略 except 子句,try 子句執行后結束。

  • 如果在執行 try 子句的過程中發生了異常,那么 try 子句余下的部分將被忽略。如果異常的類型和 except 之后的名稱相符,那么對應的 except 子句將被執行。

  • 如果一個異常沒有與任何的 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

try/except 語句還有一個可選的 else 子句,如果使用這個子句,那么必須放在所有的 except 子句之后。

else 子句將在 try 子句沒有發生任何異常的時候執行。

以下實例在 try 語句中判斷文件是否可以打開,如果打開文件時正常的沒有發生異常則執行 else 部分的語句,讀取文件內容:

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

try-finally 語句

try-finally 語句無論是否發生異常都將執行最后的代碼。

以下實例中 finally 語句無論異常是否發生都會執行:

實例

try:
    runoob()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('這句話,無論異常是否發生都會執行。')

拋出異常

Python 使用 raise 語句拋出一個指定的異常。

raise語法格式如下:

raise [Exception [, args [, traceback]]]

以下實例如果 x 大於 5 就觸發異常:

x = 10
if x > 5:
    raise Exception('x 不能大於 5。x 的值為: {}'.format(x))
執行以上代碼會觸發異常:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    raise Exception('x 不能大於 5。x 的值為: {}'.format(x))
Exception: x 不能大於 5。x 的值為: 10

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__() 被覆蓋。

<p異常的類可以像其他的類一樣做任何事情,但是通常都會比較簡單,只提供一些錯誤相關的屬性,並且允許處理異常的代碼方便的獲取這些信息。< p="">

當創建一個模塊有可能拋出多種不同的異常時,一種通常的做法是為這個包建立一個基礎異常類,然后基於這個基礎類為不同的錯誤情況創建不同的子類:

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 總是會關閉。

Python3 assert(斷言)

  Python assert(斷言)用於判斷一個表達式,在表達式條件為 false 的時候觸發異常。

斷言可以在條件不滿足程序運行的情況下直接返回錯誤,而不必等待程序運行后出現崩潰的情況,例如我們的代碼只能在 Linux 系統下運行,可以先判斷當前系統是否符合條件。

語法格式如下:

assert expression
等價於:

if not expression:
    raise AssertionError
assert 后面也可以緊跟參數:

assert expression [, arguments]
等價於:

if not expression:
    raise AssertionError(arguments)
以下為 assert 使用實例:

>>> assert True     # 條件為 true 正常執行
>>> assert False    # 條件為 false 觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1    # 條件為 true 正常執行
>>> assert 1==2    # 條件為 false 觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

>>> assert 1==2, '1 不等於 2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1 不等於 2
>>>

 

 

以下實例判斷當前系統是否為 Linux,如果不滿足條件則直接觸發異常,不必執行接下來的代碼:

實例

import sys
assert ('linux' in sys.platform), "該代碼只能在 Linux 下執行"

# 接下來要執行的代碼
 

Python Traceback詳解

  剛接觸Python的時候,簡單的異常處理已經可以幫助我們解決大多數問題,但是隨着逐漸地深入,我們會發現有很多情況下簡單的異常處理已經無法解決問題了,如下代碼,單純的打印異常所能提供的信息會非常有限。

def func1(): raise Exception("--func1 exception--") def main(): try: func1() except Exception as e: print e if __name__ == '__main__': main() 

執行后輸出如下:

--func1 exception-- 

通過示例,我們發現普通的打印異常只有很少量的信息(通常是異常的value值),這種情況下我們很難定位在哪塊代碼出的問題,以及如何出現這種異常。那么到底要如何打印更加詳細的信息呢?下面我們就來一一介紹。

sys.exc_info和traceback object

Python程序的traceback信息均來源於一個叫做traceback object的對象,而這個traceback object通常是通過函數sys.exc_info()來獲取的,先來看一個例子:

import sys def func1(): raise NameError("--func1 exception--") def main(): try: func1() except Exception as e: exc_type, exc_value, exc_traceback_obj = sys.exc_info() print "exc_type: %s" % exc_type print "exc_value: %s" % exc_value print "exc_traceback_obj: %s" % exc_traceback_obj if __name__ == '__main__': main() 

執行后輸出如下:

exc_type: <type 'exceptions.NameError'>
exc_value: --func1 exception--
exc_traceback_obj: <traceback object at 0x7faddf5d93b0>

通過以上示例我們可以看出,sys.exc_info()獲取了當前處理的exception的相關信息,並返回一個元組,元組的第一個數據是異常的類型(示例是NameError類型),第二個返回值是異常的value值,第三個就是我們要的traceback object.

有了traceback object我們就可以通過traceback module來打印和格式化traceback的相關信息,下面我們就來看下traceback module的相關函數。

traceback module

Python的traceback module提供一整套接口用於提取,格式化和打印Python程序的stack traces信息,下面我們通過例子來詳細了解下這些接口:

print_tb

import sys import traceback def func1(): raise NameError("--func1 exception--") def main(): try: func1() except Exception as e: exc_type, exc_value, exc_traceback_obj = sys.exc_info() traceback.print_tb(exc_traceback_obj) if __name__ == '__main__': main() 

輸出:

File "<ipython-input-23-52bdf2c9489c>", line 11, in main func1() File "<ipython-input-23-52bdf2c9489c>", line 6, in func1 raise NameError("--func1 exception--") 

這里我們可以發現打印的異常信息更加詳細了,下面我們了解下print_tb的詳細信息:

traceback.print_tb(tb[, limit[, file]]) 
  • tb: 這個就是traceback object, 是我們通過sys.exc_info獲取到的
  • limit: 這個是限制stack trace層級的,如果不設或者為None,就會打印所有層級的stack trace
  • file: 這個是設置打印的輸出流的,可以為文件,也可以是stdout之類的file-like object。如果不設或為None,則輸出到sys.stderr。

print_exception

import sys import traceback def func1(): raise NameError("--func1 exception--") def func2(): func1() def main(): try: func2() except Exception as e: exc_type, exc_value, exc_traceback_obj = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback_obj, limit=2, file=sys.stdout) if __name__ == '__main__': main() 

輸出:

Traceback (most recent call last): File "<ipython-input-24-a68061acf52f>", line 13, in main func2() File "<ipython-input-24-a68061acf52f>", line 9, in func2 func1() NameError: --func1 exception-- 

看下定義:

traceback.print_exception(etype, value, tb[, limit[, file]]) 
  • 跟print_tb相比多了兩個參數etype和value,分別是exception type和exception value,加上tb(traceback object),正好是sys.exc_info()返回的三個值
  • 另外,與print_tb相比,打印信息多了開頭的"Traceback (most...)"信息以及最后一行的異常類型和value信息
  • 還有一個不同是當異常為SyntaxError時,會有"^"來指示語法錯誤的位置

print_exc

print_exc是簡化版的print_exception, 由於exception type, value和traceback object都可以通過sys.exc_info()獲取,因此print_exc()就自動執行exc_info()來幫助獲取這三個參數了,也因此這個函數是我們的程序中最常用的,因為它足夠簡單

import sys import traceback def func1(): raise NameError("--func1 exception--") def func2(): func1() def main(): try: func2() except Exception as e: traceback.print_exc(limit=1, file=sys.stdout) if __name__ == '__main__': main() 

輸出(由於limit=1,因此只有一個層級被打印出來):

Traceback (most recent call last): File "<ipython-input-25-a1f5c73b97c4>", line 13, in main func2() NameError: --func1 exception-- 

定義如下:

traceback.print_exc([limit[, file]]) 
  • 只有兩個參數,夠簡單

format_exc

import logging import sys import traceback logger = logging.getLogger("traceback_test") def func1(): raise NameError("--func1 exception--") def func2(): func1() def main(): try: func2() except Exception as e: logger.error(traceback.format_exc(limit=1, file=sys.stdout)) if __name__ == '__main__': main() 

從這個例子可以看出有時候我們想得到的是一個字符串,比如我們想通過logger將異常記錄在log里,這個時候就需要format_exc了,這個也是最常用的一個函數,它跟print_exc用法相同,只是不直接打印而是返回了字符串。

traceback module中還有一些其它的函數,但因為並不常用,就不在展開來講,感興趣的同學可以看下參考鏈接中的文檔。

獲取線程中的異常信息

通常情況下我們無法將多線程中的異常帶回主線程,所以也就無法打印線程中的異常,而通過上邊學到這些知識,我們可以對線程做如下修改,從而實現捕獲線程異常的目的。

import threading import traceback def my_func(): raise BaseException("thread exception") class ExceptionThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): """ Redirect exceptions of thread to an exception handler. """ threading.Thread.__init__(self, group, target, name, args, kwargs, verbose) if kwargs is None: kwargs = {} self._target = target self._args = args self._kwargs = kwargs self._exc = None def run(self): try: if self._target: self._target() except BaseException as e: import sys self._exc = sys.exc_info() finally: #Avoid a refcycle if the thread is running a function with #an argument that has a member that points to the thread. del self._target, self._args, self._kwargs def join(self): threading.Thread.join(self) if self._exc: msg = "Thread '%s' threw an exception: %s" % (self.getName(), self._exc[1]) new_exc = Exception(msg) raise new_exc.__class__, new_exc, self._exc[2] t = ExceptionThread(target=my_func, name='my_thread') t.start() try: t.join() except: traceback.print_exc() 

輸出如下:

Traceback (most recent call last): File "/data/code/testcode/thread_exc.py", line 43, in <module> t.join() File "/data/code/testcode/thread_exc.py", line 23, in run self._target() File "/data/code/testcode/thread_exc.py", line 5, in my_func raise BaseException("thread exception") Exception: Thread 'my_thread' threw an exception: thread exception 

這樣我們就得到了線程中的異常信息。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM