python - 忽略在 python 3 中向调用者引发异常

标签 python python-3.x exception pep

如何忽略 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 中,异常在函数内部仍然保持事件状态:

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())

调用相同的函数:

foo()    
(None, None, None)

关于python - 忽略在 python 3 中向调用者引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057162/

相关文章:

flutter - 如何创建自定义异常并在 dart 中处理它

python - Keras:在 theano 和 tensorflow 之间转换预训练的权重

python - Tweepy - 获取访问 token 时出错 : "argument 2 to map() must support iteration"

python - 扩展分层数据,根据列中的列表项创建新行

python - 检测单个字符串分数(例如 : ½ ) and change it to longer string?

python-3.x - 激活python virtualenv后如何自动运行shell脚本?

c# - 堆栈跟踪中的敏感信息

python - PyQt4,matplotlib,修改现有绘图的轴标签

python - 完整的 conda-forge channel 网址是什么?

c# - 处理 "application not found"等特定 Win32 异常的最佳方法是什么?