Are the else
and finally
sections of exception handling redundant? For example, is there any difference between the following two code snippets?
finally
block always executed
Else
block executed If there is not any exception.
I prefer to put the code in finally
block which is always executed after try
and except blocks.
I prefer to put the code in else
block which is executed if the try
clause does not raise an exception
same like this
Finally
try:
f = open("file.txt")
f.write("change file")
except:
print("wrong")
finally:
f.close()
Else
try:
f = open("file.txt")
f.write("change file")
except:
print("wrong")
else:
print("log => there is not any exception")
finally:
f.close()
If you move the contents of the else
block inside the try
block, you will also catch exceptions that might happen during the else
block. If the line
print(foo.read())
in your example throws an IOError
, your first code snippet won't catch that error, while your second snippet will. You try to keep try
blocks as small as possible generally to really only catch the exceptions you want to catch.
The finally
block gets always executed, no matter what. If for example the try
block contains a return
statement, a finally
block will still be executed, while any code beneath the whole try
/except
block won't.
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.
try:
print("I may raise an exception!")
except:
print("I will be called only if exception occur!")
else:
print("I will be called only if exception didn't occur!")
finally:
print("I will be called always!")
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.