簡體   English   中英

Python 在單行記錄多個錯誤

[英]Python Logging Multiple Errors on Single Line

我正在嘗試記錄一些預期的錯誤。

最初,我編寫的腳本如下:

   except (BadZipFile, MemoryError) as e:
       logger.error(f'No: {n} - {filename} = {e}')

但我注意到在記錄器中,似乎只有BadZipFile錯誤消息出現了。 MemoryError日志在=符號后似乎是空白的

我想也許e只是存儲BadZipFile錯誤消息,因為它首先出現,所以我嘗試制作一個元組:

   except (BadZipFile, MemoryError) as (eb, em):
       logger.error(f'No: {n} - {filename} = {eb, em}')

但當然語法是錯誤的。 那么我的代碼最初出了什么問題? 為什么不存儲MemoryError日志?

當程序發生異常時將停止執行並移至except塊。 因此,當發生異常時,不可能在同一個try塊中獲取另一個異常。 所以總是會收到一份異常日志。

讓我用一些代碼來解釋一下,考慮到我們有兩種類型的錯誤, IndexErrorZeroDivisionError

情況1:

>>> l = []
>>> a = 1
>>> b = 0
>>> try:
...     x = l[0]
...     y = a/b
... except (IndexError, ZeroDivisionError) as e:
...     print(e)
...
list index out of range

案例2:

>>> try:
...     x = a/b
...     y = l[0]
... except (IndexError, ZeroDivisionError) as e:
...     print(e)
...
division by zero

案例三:

>>> try:
...     x = l[0]/b
... except (IndexError, ZeroDivisionError) as e:
...     print(e)
...
list index out of range
>>>

Case1,首先引發 IndexError,因此使用 IndexError 調用 bock 除外
Case2,首先引發 ZeroDivisionError,因此使用 ZeroDivisionError 調用 except 塊
Case3,即使兩個異常都在單行中,但執行行發生在索引中,因此引發了 IndexError。

編輯:

在您的情況下,首先引發BadZipFile異常,因此您的 except 塊except (BadZipFile, MemoryError) as e:被調用時帶有BadZipFile異常。 這就是為什么你的 output 對於MemoryError是空的。

即使MemoryError首先引發空 arguments 然后它也不會記錄任何內容。

>>> try:
...     raise MemoryError("This is memory error")
... except MemoryError as e:
...     print(e)
...
This is memory error
>>> try:
...     raise MemoryError()
... except MemoryError as e:
...     print(e)
...

>>> 

無論哪個異常先發生,都會被 except 塊捕獲。 所以,我認為在你的情況下,第一個異常引發是 BadZipFile。 參考@LMKR 示例。

嘗試顯式引發異常以檢查它是否正常工作......

>>> try:
...     if True:
...         raise MemoryError("MemoryError occured")
... except (BadZipFile, MemoryError) as e:
...     print(e)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM