Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure how real-world your example is, but there's no need to a) catch each exception separately, if you don't handle them differently, or b) catch them at all, in many cases.</p> <p>What you're doing in your example, just printing a stack trace, is a bad idea in almost all cases. You're printing messy information to a place where no one's likely paying attention.</p> <p>I follow two general guidelines: </p> <ol> <li>Handle the exception at the point at which it's thrown, if you can (to close an open file on a file access exception, for instance, or retry a troublesome interface (<em>stupid unreliable bespoke USB devices...</em>)). </li> <li>Allow the exception to bubble up to a point higher in your stack, where you can catch all exceptions you can't otherwise handle. Log them, display them, or kill your application, whatever makes the most sense. </li> </ol> <p>I'll illustrate the second point with some code, <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="nofollow"><strike>stolen from</strike> inspired by the Java tutorials</a>.</p> <pre><code>private String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } </code></pre> <p>Here, we've defined a method that attempts to read from a file. Lots of things can go wrong here, but there's nothing the code at this level is going to do about that. Instead, it's going to pass the buck to the method that called it, with the <code>throws</code> clause. That calling method may handle the exception itself, or pass the buck to <em>its</em> caller, with the same clause:</p> <pre><code>private String readAllTheFiles() throws IOException { for (...) { readFirstLineFromFile(...); } } </code></pre> <p>Now, there's <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html" rel="nofollow">lots of debate</a> around why Java requires the <code>throws</code> in this case. Many other languages don't use them, for better or worse. You'll often see <code>RuntimeExceptions</code> - exceptions that don't require a <code>throws</code> clause. If your method might throw an exception that extends from <code>RuntimeException</code>, you <strong>don't</strong> need to declare that fact in a <code>throws</code>.</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