2016-08-20 36 views
1

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

+2

如果你看到一些地方外'except'块在实际的程序被触发,你有一些其他问题没有反映在你的问题中。你问题中的代码结构决不应该触发外部'except'块。 – user2357112

回答

1

没有必要在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)