Why does the exception in foo
whizz by unnoticed, but the exception in bar
is raised?
def foo(): try: raise Exception('foo') finally: return def bar(): try: raise Exception('bar') finally: pass foo() bar()
The finally keyword is used in try... except blocks. It defines a block of code to run when the try... except...else block is final. The finally block will be executed no matter if the try block raises an error or not.
When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement.
From the Python documentation:
If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.
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