MedAl
MedAl

Reputation: 475

Handle exception without try/catch

I have got a method where the exceptions thrown have to be handled by the caller, and not by the method itself (exceptions specified in the signature and not in the body). However, in case of something bad happening, I would like to use something similar to a finallystatement to close my reader before the caller has to deal with the problem.

In the current configuration, if an exception is triggered, the reader remains open.

private static void executeFile(Connection c, String fileName) throws SQLException, IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.defaultCharset())); // $JL-I18N$

    /*
        Lot of stuff happen here, and might trigger exceptions
    */

    reader.close();

}

Is there a way to handle this case ? Or should the method be refactored to handle exceptions by itself ?

EDIT

Some good tips have been provided in the comments. The solution I finally chose considering this was to extract the code triggering the warning and using a try-with-resources.

Upvotes: 0

Views: 1613

Answers (1)

Stephen C
Stephen C

Reputation: 719436

This is how you do it. Use try-with-resources.

private static void executeFile(Connection c, String fileName)
       throws SQLException, IOException {
    try (InputStream is = new FileInputStream(fileName);
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader reader = new BufferedReader(isr)) {
        /* Lots of stuff */
    }
}

Exceptions thrown in the try block will be propagated, and the reader stack will be closed. If (hypothetically) the implicit close() performed by the try-with-resource was to throw an exception:

  • it would be suppressed if another exception already propagating,
  • otherwise it would be propagated.

Note that I have rewritten `

    new InputStreamReader(is, Charset.defaultCharset())

as

    new InputStreamReader(is)

because they are equivalent: check the javadoc. The other rewriting was solely for readability, though it does illustrate that try-with-resources can manage multiple resources.

Upvotes: 1

Related Questions