简体   繁体   中英

How to handle multiple exceptions

If I have a code that raises more exceptions simultaniously like this

class A(Exception): pass
class B(Exception): pass

try:
    try:
        raise A('first')
    finally:
        raise B('second')
except X as c:
    print(c)

Is there a way for handle all the exceptions toghether?

You can handle them all in this way:

except (A, B) as c:

Also you can define your own base class for your exceptions:

class BaseCustomException(Exception): pass
class A(BaseCustomException): pass
class B(BaseCustomException): pass

After it you can catch base exception, it will cover all derived exceptions:

except BaseCustomException as c:

When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.

check: Exception thrown in catch and finally clause

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