Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try-finally

Tags:

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() 
like image 432
wim Avatar asked Dec 20 '11 11:12

wim


People also ask

What is try finally in Python?

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.

Can I use try and finally in Python?

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.

What is the use of try finally clause?

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.


1 Answers

From the Python documentation:

If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.

like image 95
interjay Avatar answered Oct 01 '22 13:10

interjay