La bla bla
La bla bla

Reputation: 8708

try catch in finally section

Is it considered bad programming to write a try and catch within a finally clause?

I'm having in my main method a fileInputStream which I want to close. I want to place the .close() in the finally, so it will close no matter what. I don't want to add a throws declaration to the main method, as it is the main method :P

    }finally{
        try {
            commandFile.close();
        } catch (IOException e) {
            throwException(e);
        }
    }

is it ok? Thanks

Upvotes: 9

Views: 3484

Answers (1)

Arjan Tijms
Arjan Tijms

Reputation: 38163

The pattern of needing try/catches in finally methods is unfortunately a recurring pattern in Java 6 and before. I would argue that it actually IS a bad practice, but not one that you can really avoid in Java 6 (see below for Java 7).

An addition problem is that any new exceptions thrown in the finally block will override exceptions that were thrown before reaching this block.

In Java 7 there is specifically for the cases where resources need to be closed (the majority of the use cases for try/finally/try/catch constructs) the new try-with-resources construct. This will also capture both the primary and secondary exceptions.

Using this construct is thus now a best practice in JDK 7 and yes, the code you show is thus a bad practice in Java 7.

Upvotes: 9

Related Questions