Note that there are some explanatory texts on larger screens.

plurals
  1. POHow much code to put in try-catch block
    text
    copied!<p><strong>Is there a "best practice" for how much code to put inside a <code>try/catch</code> block?</strong></p> <p>I have posted 3 different scenarios below.</p> <p><em>I did not include behavior in each <code>catch</code> block and i did not include the finally block. This was to improve readability for viewers. Assume each <code>catch</code> does something differently. And assume the <code>finally</code> will be closing the stream. Just trying to create an easy to read example for future readers.</em></p> <ol> <li>Control, no <code>try/catch</code>.</li> <li>Code with 1 <code>try/catch</code> for each place needed.</li> <li>Code with only 1 <code>try/catch</code> surrounding whole code block.</li> </ol> <p><strong>What is generally accepted as the best practice and why?</strong></p> <hr> <p><strong>Scenario 1</strong></p> <p>Code without <code>try/catch</code>, just for control.</p> <pre><code> BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath")); String line; while ((line = bufferedReader.readLine()) != null) { Object object = new Object(); this.doSomething(object); } bufferedReader.close(); </code></pre> <hr> <p><strong>Scenario 2</strong></p> <p>Code with a <code>try/catch</code> block for each individual place needed.</p> <pre><code> BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader("somepath")); } catch (FileNotFoundException e) { e.printStackTrace(); } String line; try { while ((line = bufferedReader.readLine()) != null) { Object object = new Object(); this.doSomething(object); } } catch (IOException e) { e.printStackTrace(); } try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } </code></pre> <hr> <p><strong>Scenario 3</strong></p> <p>Code with 1 <code>try/catch</code> surrounding the whole block of code.</p> <pre><code> try { BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath")); String line; while ((line = bufferedReader.readLine()) != null) { Object object = new Object(); this.doSomething(object); } bufferedReader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre>
 

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