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?
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.
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.
The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.
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.
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.
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.
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