Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: checked vs unchecked exception explanation
    text
    copied!<p>I have read multiple posts on StackOverFlow about checked vs unchecked exceptions. I'm honestly still not quite sure how to use them properly. </p> <p>Joshua Bloch in "<em>Effective Java</em>" said that </p> <blockquote> <p>Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)</p> </blockquote> <p>Let's see if I understand this correctly.</p> <p>Here is my understanding of a checked exception:</p> <pre><code>try{ String userInput = //read in user input Long id = Long.parseLong(userInput); }catch(NumberFormatException e){ id = 0; //recover the situation by setting the id to 0 } </code></pre> <p><strong>1. Is the above consider a checked exception?</strong></p> <p><strong>2. Is RuntimeException an unchecked exception?</strong></p> <p>Here is my understanding of an unchecked exception:</p> <pre><code>try{ File file = new File("my/file/path"); FileInputStream fis = new FileInputStream(file); }catch(FileNotFoundException e){ //3. What should I do here? //Should I "throw new FileNotFoundException("File not found");"? //Should I log? //Or should I System.exit(0);? } </code></pre> <p><strong>4. Now, couldnt the above code also be a checked exception? I can try to recover the situation like this? Can I?</strong> (Note: my 3rd question is inside the <code>catch</code> above)</p> <pre><code>try{ String filePath = //read in from user input file path File file = new File(filePath); FileInputStream fis = new FileInputStream(file); }catch(FileNotFoundException e){ //Kindly prompt the user an error message //Somehow ask the user to re-enter the file path. } </code></pre> <p><strong>5. Why do people do this?</strong></p> <pre><code>public void someMethod throws Exception{ } </code></pre> <p>Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up? </p> <p><strong>EDIT: Should I bubble up the exact exception or mask it using Exception?</strong></p> <p><strong>Below are my readings</strong></p> <p><a href="https://stackoverflow.com/questions/499437/in-java-when-should-i-create-a-checked-exception-and-when-should-it-be-a-runtim">In Java, when should I create a checked exception, and when should it be a runtime exception?</a></p> <p><a href="https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions">When to choose checked and unchecked exceptions</a></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