How to determine if an exception was raised once you're in the finally block?

后端 未结 6 1764
一整个雨季
一整个雨季 2020-12-14 06:06

Is it possible to tell if there was an exception once you\'re in the finally clause? Something like:

try:
    funky code
finally:
    if ???:
          


        
6条回答
  •  悲&欢浪女
    2020-12-14 07:04

    You can easily assign your caught exception to a variable and use it in the finally block, eg:

    >>> x = 1
    >>> error = None
    >>> try:
    ...     x.foo()
    ... except Exception as e:
    ...     error = e
    ... finally:
    ...     if error is not None:
    ...             print(error)
    ...
    'int' object has no attribute 'foo'
    

提交回复
热议问题