[英]Ignore raising exception to the caller in python 3
How can I ignore a certain exception to be raised to the caller in python 3?如何忽略 python 3 中向调用方引发的某个异常?
Example:例子:
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
I found someone mentioned that " Because of the last thrown exception being remembered in Python, some of the objects involved in the exception-throwing statement are being kept live indefinitely " and then mentioned to use "sys.exc_clear()" in this case which is not available anymore in python 3. Any clue how can I completely ignore the exception in python3?我发现有人提到“由于在 Python 中记住了最后抛出的异常,异常抛出语句中涉及的一些对象将无限期地保持存在”,然后提到在这种情况下使用“sys.exc_clear()”在 python 中不再可用 3. 任何线索我怎样才能完全忽略 python3 中的异常?
There's no need to do this in Python 3
, sys.exc_clear()
was removed because Python doesn't store the last raised exception internally as it did in Python 2:在 Python
3
中不需要执行此操作, sys.exc_clear()
已被删除,因为 Python 不像在 Python 2 中那样在内部存储最后引发的异常:
For example, in Python 2, the exception is still kept alive when inside a function:例如,在 Python 2 中,异常在 function 内部仍然保持活动状态:
def foo():
try:
raise ValueError()
except ValueError as e:
print(e)
import sys; print(sys.exc_info())
Calling foo
now shows the exception is kept:现在调用
foo
显示异常被保留:
foo()
(<type 'exceptions.ValueError'>, ValueError(), <traceback object at 0x7f45c57fc560>)
You need to call sys.exc_clear()
in order to clear the Exception
raised.您需要调用
sys.exc_clear()
才能清除引发的Exception
。
In Python 3, on the contrary: Python 3、反之:
def foo():
try:
raise ValueError()
except ValueError as e:
print(e)
import sys; print(sys.exc_info())
Calling the same function:调用相同的 function:
foo()
(None, None, None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.