简体   繁体   中英

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 finally statement 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM