Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>... but I don't really get the point of using these instead of just having catches in every function.</p> </blockquote> <p>The point is that next function up the call stack may not know how to handle the exception. Example:</p> <pre><code>public class Test { public Object doSomething(String source) throws IOException { try (InputStream is = openAsStream(source)) { // ... read and process stuff return ... } } public InputStream openAsStream(String name) throws IOException { String fileName = // ... do something with 'name' return new FileInputStream(name); } public static void main(String[] args) { // ... Test t = new Test(); try { t.doSomething(args[0]); } catch (IOException ex) { System.err.println("Cannot handle '" + args[0] + "'"); } } } </code></pre> <p>The <code>openAsStream</code> calls the <code>FileInputStream</code> constructor which may throw an <code>IOException</code>. The <code>openAsStream</code> method cannot recover from this so it lets it propagate. The <code>doSomething</code> method doesn't know how to deal with it either, so it allows it to propagate. Finally, the exception gets to <code>main</code> ... which knows how to explain the problem to the user.</p> <hr> <p>Now you could write <code>openAsStream</code> to catch the <code>IOException</code>, print an error message and return a <code>null</code>. But that would be a big mistake:</p> <ul> <li><p>The <code>openAsStream()</code> doesn't (and <em>shouldn't</em>) know whether / how to report the problem to the user. </p></li> <li><p>And if it returns a <code>null</code> to the caller, then the caller has to test to see whether the result of the call is <code>null</code> ... and take alternative action.</p></li> </ul> <p>The point is that a method should only handle exceptions that can be adequately dealt with at that level. Others should be allowed to propagate. (Or maybe wrapped in another exception ... if that is what the API design requires.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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