Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Lets consider the class:</p> <pre><code>public class Resource implements AutoCloseable { public Resource() throws Exception { throw new Exception("Exception from constructor"); } public void doSomething() throws Exception { throw new Exception("Exception from method"); } @Override public void close() throws Exception { throw new Exception("Exception from closeable"); } } </code></pre> <p>and the try-with-resource block:</p> <pre><code> try(Resource r = new Resource()) { r.doSomething(); } catch (Exception ex) { ex.printStackTrace(); } </code></pre> <p><strong>1.</strong> All 3 throw statements enabled.</p> <p>Message "Exception from constructor" will printed and the exception thrown by constructor will be <strong>suppressed</strong>, that means you can't catch it.</p> <p><strong>2.</strong> The throw in constructor is removed.</p> <p>Now the stack trace will print "Exception from method" and "Suppressed: Exception from closeable" below. Here you also can't catch the suppressed exception thrown by close method, but you will be nofitied about the suppressed exception.</p> <p><strong>3.</strong> Throws from constructor and method are removed.</p> <p>As you have probably already guessed the "Exception from closeable" will be printed.</p> <p><strong>Important tip:</strong> In all of above situations you are actually <strong>catching all exceptions</strong>, no matter where they were throwed. So if you use try-with-resource block you don't need to wrap the block with another try-catch, it's simply useless.</p> <p>Hope it helps :)</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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