The idea of try-with-resources is to make sure that resources must be closed.
The problem with regular try-catch-finally is that let your try block throw an exception; Now you usually handle this exception in the finally block.
Now suppose that an exception also occurs in the finally block. In this case, the exception caused by the catch attempt is lost and an exception is thrown that is thrown in the finally block.
try { // use something that using resource // eg, streams } catch(IOException e) { // handle } finally { stream.close(); //if any exception occurs in the above line, than that exception //will be propagated and the original exception that occurred //in try block is lost. }
In try-with-resources the close() try-with-resources method will be called automatically, and if close() throws any exception, the rest of the finally will not be reached, and the original exception will be lost.
Compare this to this:
try (InputStream inputStream= new FileInputStream("C://test.txt")){ // ... use stream } catch(IOException e) { // handle exception }
in the above code snippet, the close() method is automatically called, and if this close() method also throws any exception, then this exception will be automatically suppressed.
See also: Java Language Specification 14.20.3
Raman Sahasi Nov 02 '16 at 12:09 2016-11-02 12:09
source share