Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"raise" at the end of a python function outside "try" or "except" block

What does raise do, if it's not inside a try or except clause, but simply as the last statement in the function?

def foo(self):
    try:
        # some code that raises an exception
    except Exception as e:
        pass

    # notice that the "raise" is outside
    raise

This example prints 1 but not 2 so it must be that the last raise statement simply raises the last thrown exception.

def foo():
    try:
        raise Exception()
    except Exception as e:
        pass

    print 1
    raise
    print 2

if __name__ == '__main__':
    foo()

Any official documentation for this type of usage pattern?

like image 635
gli Avatar asked Dec 12 '22 03:12

gli


1 Answers

As Russell said,

A bare raise statement re-raises the last caught exception.

It doesn't matter whether this is happening in a try-except block or not. If there has been a caught exception, then calling raise will re-raise that exception. Otherwise, Python will complain that the previously caught exception is None and raise a TypeError because None is not something that can actually be raised.

As tdelaney said, it doesn't seem to make sense to do this except in an error-handling function. Personally I'd say that it doesn't even belong in an error-handling function, as the raise should still be in the except clause. Someone could use this in an attempt to execute code whether or not an error occurs, but a finally clause is the proper way to do that. Another possibility would be using this as a way to determine if an error occurred while executing the function, but there are much better ways to do that (such as returning an extra value that indicates if/where an error occurred).

like image 159
Rob Watts Avatar answered May 11 '23 15:05

Rob Watts