Raising exceptions when an exception is already present in Python 3

前端 未结 5 1682
感情败类
感情败类 2020-12-14 05:52

What happens to my first exception (A) when the second (B) is raised in the following code?

class A(Exception): pass
class B(Except         


        
5条回答
  •  臣服心动
    2020-12-14 06:28

    Pythons exception handling will only deal with one exception at a time. However, exception objects are subject to the same variable rules and garbage collection as everything else. Hence, if you save the exception object in a variable somewhere you can deal with it later, even if another exception is raised.

    In your case, when an exception is raised during the "finally" statement, Python 3 will print out the traceback of the first exception before the one of the second exception, to be more helpful.

    A more common case is that you want to raise an exception during an explicit exception handling. Then you can "save" the exception in the next exception. Just pass it in as a parameter:

    >>> class A(Exception):
    ...     pass
    ... 
    >>> class B(Exception):
    ...     pass
    ... 
    >>> try:
    ...     try:
    ...         raise A('first')
    ...     except A as e:
    ...         raise B('second', e)
    ... except Exception as c:
    ...     print(c.args[1])
    ... 
    first
    

    As you see you can now access the original exception.

提交回复
热议问题