Be Pissed, Be Polite. Always Say "good Bye!" (the Reason Behind 'finally' In A Try:catch)
There has been a lot of debate about exceptions and their usage in the Java world. This post is not about it.
A foreword on what exceptions really are in case you are still confused.
Consider yourself going to your local store to buy a muffin (an addict here).
Now I prefer a chocolate one but the local store might not have one. So I walk in, go to the muffins section and… there is none! Something unexpected happened (hint an Exception). Yeah I’m pissed but I still have to be polite and say goodbye on my way out.
Now the only way to ensure that; is the ‘finally’ clause in a try/catch block. Here is why.
Without a ‘finally’ this might very well work. You do handle the exception right there and you still get to say “Good bye!” at the end. There are 2 things to consider though.
LocalStore#buyMuffin(Flavour)method might very well change (especially if it’s third party code) introducing a new exception to the mix (
InsufficientFundsExceptionsince people were just buying muffins without having enough money to pay). You aren’t being polite anymore.
- you may not be responsible for handling the situation of not having enough money to buy a muffin. Your dad/employer/clients are. (in the “real world” an example would be to have a common class to log the exceptions)
Now in both cases not having a
finally clause will simply break your code sooner or later. (Picture this with database connections and you have a serious leak there)
Disclaimer Take the advice. Not the code. It’s just an example.