I have some questions regarding handling exceptions in Java. I read a bit about it and got some contradicting guidelines.
Best Practices for Exception Handling
Let's go through the mentioned article:
It states that one should generally avoid using checked exceptions if "Client code cannot do anything". But what does it exactly mean? Is displaying error message in GUI sufficient reason for bubbling up checked exception? But it would force GUI programmer to remember to catch RuntimeExceptions and their descendants to display potential error info.
Second view presented in this article is that one should evade inventing own exception classes unless I want to implement some customs field/methods in them. I generally disagree with this, my practice up today was just the opposite: I wrapped exceptions in my own exception structure to reflex goals realized by classes I write, even if they just extend Exception without adding any new methods. I think it helps to handle them more flexibly in the higher layers when thrown plus it's generally more clear and comprehensible for programmer who will use these classes.
I implemented some code today 'new way' presented in the article throwing RuntimeException here and there, then I let Sonar analyze it. To confuse me even more Sonar marked my RuntimeExceptions as Major errors with a message like "Avoid throwing root type exceptions, wrap'em in your own types".
So it looks quite controversional, what do you think?
I also heard from one of tech-leads today that just wrapping exceptions is bad, 'because it's a really costly operation for JVM'. For me, on the other side throwing SQLExceptions or IOExceptions everywhere looks like a bit of breaking encapsulation..
So what is your general attitude to questions I presented here?
When to wrap exceptions in my own types, when I shouldn't do this?
Where is that point of 'client cannot do anything about this, throw runtime exception?'
What about performance issues?
An unchecked exception (also known as an runtime exception) in Java is something that has gone wrong with the program and is unrecoverable. Just because this is not a compile time exception, meaning you do not need to handle it, that does not mean you don't need to be concerned about it.
It is an essential concept never catch any exception so catch any exception only if you can handle it you can give additional contextual data in that exception. If you can't handle it in the catch block, then the best advice is don't catch it only to re-throw it.
It looks like your tech-lead, as often, has escaped his role of developer because he wasn't good at it.
My advices would be:
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