Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of else and finally in exception handling

Tags:

python

Are the else and finally sections of exception handling redundant? For example, is there any difference between the following two code snippets?

try:     foo = open("foo.txt") except IOError:     print("error") else:     print(foo.read()) finally:     print("finished") 

and

try:     foo = open("foo.txt")     print(foo.read()) except IOError:     print("error") print("finished") 

More generally, can't the contents of else always be moved into the try, and can't the contents of finally just be moved outside the try/catch block? If so, what is the purpose of else and finally? Is it just to enhance readability?

like image 379
jhourback Avatar asked May 18 '11 22:05

jhourback


People also ask

What is the purpose of a finally clause?

Answer: finally is usually used to close a code properly after its encountered an Exception or Error. This means that no matter whether an exception/error comes or not, 1nce the try/try-catch block ends, the finally block WILL be executed.

What is the difference between else block and finally block in exception handling?

Else block runs only when no exceptions occur in the execution of the try block. Finally block always runs; either an exception occurs or not.

What is the purpose of finally class?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.

What is the purpose of try except else?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.


2 Answers

finally is executed regardless of whether the statements in the try block fail or succeed. else is executed only if the statements in the try block don't raise an exception.

like image 111
Brian Fisher Avatar answered Sep 24 '22 13:09

Brian Fisher


No matter what happens, the block in the finally always gets executed. Even if an exception wasn't handled or the exception handlers themselves generate new exceptions.

like image 31
orlp Avatar answered Sep 23 '22 13:09

orlp