[英]Ignore raising exception to the caller in python 3
如何忽略 python 3 中向調用方引發的某個異常?
例子:
def do_something():
try:
statement1
statement2
except Exception as e:
# ignore the exception
logging.warning("this is normal, exception is ignored")
try:
do_something()
except Exception as e:
# this is unexpected control flow, the first exception is already ignored !!
logging.error("unexpected error")
logging.error(e) # prints None
我發現有人提到“由於在 Python 中記住了最后拋出的異常,異常拋出語句中涉及的一些對象將無限期地保持存在”,然后提到在這種情況下使用“sys.exc_clear()”在 python 中不再可用 3. 任何線索我怎樣才能完全忽略 python3 中的異常?
在 Python 3
中不需要執行此操作, sys.exc_clear()
已被刪除,因為 Python 不像在 Python 2 中那樣在內部存儲最后引發的異常:
例如,在 Python 2 中,異常在 function 內部仍然保持活動狀態:
def foo():
try:
raise ValueError()
except ValueError as e:
print(e)
import sys; print(sys.exc_info())
現在調用foo
顯示異常被保留:
foo()
(<type 'exceptions.ValueError'>, ValueError(), <traceback object at 0x7f45c57fc560>)
您需要調用sys.exc_clear()
才能清除引發的Exception
。
Python 3、反之:
def foo():
try:
raise ValueError()
except ValueError as e:
print(e)
import sys; print(sys.exc_info())
調用相同的 function:
foo()
(None, None, None)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.