Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 220
La bla bla Avatar asked Apr 01 '12 14:04

La bla bla


People also ask

Can we use try catch in finally block?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

What is finally in try catch Java?

The catch Blocks. The finally Block. The try-with-resources Statement. Putting It All Together. Specifying the Exceptions Thrown by a Method.

Is finally mandatory in try catch?

Yes you can write try without catch. In that case you require finally block. Try requires either catch or finally or both that is at least one catch or finally is compulsory.

How many finally {} blocks may be there in a try catch structure?

Here is the try/catch/finally structure. There can only be one finally block, and it must follow the catch blocks. If the try block exits normally (no exceptions occurred), then control goes directly to the finally block. After the finally block is executed, the statements following it get control.


1 Answers

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.

like image 194
Arjan Tijms Avatar answered Oct 14 '22 18:10

Arjan Tijms