简体   繁体   中英

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?

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?

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:

For example, in Python 2, the exception is still kept alive when inside a 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()
(<type 'exceptions.ValueError'>, ValueError(), <traceback object at 0x7f45c57fc560>)

You need to call sys.exc_clear() in order to clear the Exception raised.

In Python 3, on the contrary:

def foo():
    try:
        raise ValueError()
    except ValueError as e:
        print(e)
    import sys; print(sys.exc_info())

Calling the same function:

foo()    
(None, None, None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM