Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of <code>RuntimeException</code> (unchecked exception)</p> <p>However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.</p> <p><a href="http://techblog.bozho.net/?p=316" rel="noreferrer">Here's my extended view on the topic</a>.</p> <p>As for the particular questions:</p> <ol> <li><p><strong>Is the <code>NumberFormatException</code> consider a checked exception?</strong><br> No. <code>NumberFormatException</code> is unchecked (= is subclass of <code>RuntimeException</code>). Why? I don't know. (but there should have been a method <code>isValidInteger(..)</code>)</p></li> <li><p><strong>Is <code>RuntimeException</code> an unchecked exception?</strong><br> Yes, exactly.</p></li> <li><p><strong>What should I do here?</strong><br> It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:</p> <ul> <li>log it and return</li> <li>rethrow it (declare it to be thrown by the method)</li> <li>construct a new exception by passing the current one in constructor </li> </ul></li> <li><p><strong>Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?</strong><br> It could've been. But nothing stops you from catching the unchecked exception as well</p></li> <li><p><strong>Why do people add class <code>Exception</code> in the throws clause?</strong><br> Most often because people are lazy to consider what to catch and what to rethrow. Throwing <code>Exception</code> is a bad practice and should be avoided.</p></li> </ol> <p>Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload