This Python eats Exceptions
Python like any other modern language has exception management. But I ran into an interesting edge case that stumped me quite a bit before I realized well python is different.
Let me explain with an example.
|
|
You would expect this to print
|
|
ie the try, the catch the finally block and then the exception should bubble up to the top layer and since we are not handling it, it should fail.
But Surprise, surprise, we dont see the final exception. The output looks like
Inside try block
Exception caught in catch Block
In the finally block
So the Ex2 which was supposed to bubble up was swallowed by Python. I tried running it under both Python 3.9.5 and Python 2.7.17 and the results are the same. So I went spelunking into the python documentation and found something very interesting.
If the finally clause executes a break, continue or return statement, exceptions are not re-raised.
So that small return -1 made the difference. Once I removed it, the code behaved as expected.
That is python for you. So be careful what you do in your finally
clause
especially when you are returning values, any exception that you throw in your
except blocks will be swallowed!
I decided to try this out in Java, the tried and trusted enterprise powerhouse language.
|
|
And Java shows the exact same behavior as Python. This program runs with the following output
|
|
Removing the return statement in the finally block brings out the same behavior as python. So I guess learned an important lesson -
finally {}
blocks is not a great place to return a value because they could potentially supress the
exceptions being raised within the exception blocks.
Yes I realise the title is misleading it is not just python but Java too is eating exceptions. I found this behavior in Python code so that is the reason wrote the title but I realised when I was researching this idea, Java too had the same behavior.