Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is checking for exceptions in code or using try-catch a better practice in Java?

I had someone mention to me that catching all exceptions is not necessarily good practice (for example, NullPointerException). I am looking for an explanation of when this is a good thing, when it is not, and why it is as such :D

Thanks!!

badPanda

like image 985
badpanda Avatar asked Mar 18 '10 18:03

badpanda


3 Answers

In short:

Checked exceptions are for catching

Unchecked exceptions and errors can be left to bubble up. (these are the subclasses of RuntimeException and Error).

This is because checked exceptions are "expected" and the program can recover from them. Unchecked exceptions are such from which the program cannot recover (easily).

Sun's tutorial says (it's about deciding what kind of exception you should create, but it is also informative on the other side - i.e. when using exceptions):

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

like image 113
Bozho Avatar answered Oct 18 '22 23:10

Bozho


To further Bozho's post checked exceptions typically handle exceptions you expect to happen regardless of how perfect your code is (ie: a network cable is unplugged and you catch and IO exception). You declare they methods throw checked exceptions as other code must deal with how to handle these exceptions.

Unchecked exceptions tend to be used for unexpected conditions for example NullPointerExceptions often bubble up because the program should have thrown a checked exception, filtered data, set defaults, etc. They are unchecked and often unexpected, thus you do not have to catch them.

This is not true 100% of the time but as a general approach that is how it works, in Java especially.

like image 3
benstpierre Avatar answered Oct 18 '22 22:10

benstpierre


And adding to bozho's answer, it sometimes depends on the type of application as well, as you in some case you may have to handle it to perform some work around for that, and in some case you can leave it to handle by the caller or ultimately to terminate.

like image 2
GuruKulki Avatar answered Oct 18 '22 21:10

GuruKulki