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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With