Can I get the exception from the finally block in python?

前端 未结 4 888
夕颜
夕颜 2020-12-04 23:56

I have a try/finally clause in my script. Is it possible to get the exact error message from within the finally clause?

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 00:21

    Actually, other answers are bit vague. So, let me clarify it. You can always invoke sys.exc_info() from finally block. However, its output will vary depending whether exception has been actually raised.

    import sys
    
    def f(i):
    
        try:
            if i == 1:
                raise Exception
        except Exception as e:
            print "except -> " + str(sys.exc_info())
        finally:
            print "finally -> " + str(sys.exc_info())
    
    f(0)
    f(1)
    
    >>> 
    finally -> (None, None, None)
    except -> (, Exception(), )
    finally -> (, Exception(), )
    

    Thus, you can always know in finally block, whether exception was raised, if it's first level function. But sys.exc_info() will behave differently when length of call stack exceeds 1, as shown in below example. For more information, refer to How sys.exc_info() works?

    import sys
    
    def f(i):
    
        try:
            if i == 1:
                raise Exception
        except Exception as e:
            print "except -> " + str(sys.exc_info())
        finally:
            print "finally -> " + str(sys.exc_info())
    
    def f1(i):
        if i == 0:
            try:
                raise Exception('abc')
            except Exception as e:
                pass
    
        f(i)
    
    f1(0)
    f1(1)
    
    >>> 
    finally -> (, Exception('abc',), )
    except -> (, Exception(), )
    finally -> (, Exception(), )
    

    I hope, it makes things bit clearer.

提交回复
热议问题