2016-08-20 52 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)