1

如何忽略在 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 中的异常?

4

1 回答 1

1

在 Python 中没有必要这样做3sys.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)
于 2016-08-20T19:08:36.793 回答