9

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

user
  • 5,335
  • 7
  • 47
  • 63
La bla bla
  • 8,558
  • 13
  • 60
  • 109
  • 8
    Yes this is OK and is sometimes necessary. – Hovercraft Full Of Eels Apr 01 '12 at 14:11
  • 1
    If you are just going to rethrow the exception you don't need the try catch. The try catch is necessary because you are supposed to do something with the exception (at the bare minimum, logging it), if you decide not to then it is not necessary. – SJuan76 Apr 01 '12 at 14:16
  • I need to print something to System.err and then System.exit That's what the throwExcpetion(e) method does – La bla bla Apr 01 '12 at 14:18
  • 3
    Also consider try-with-resource at http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Java42 Apr 01 '12 at 14:19
  • Yep, the general concept of a try/catch/finally inside a finally clause is fine. And the above example of converting an exception from one type to another is one reason you might do this. If you're going to do a lot inside the finally clause, though, you may wish to consider breaking it out as a separate method. – Hot Licks Apr 01 '12 at 14:20
  • 1
    It's a bad practice if you'd ask me. It makes code hard to read and verbose. This kinds of constructs gave Java a bad name. – Mike Braun Apr 01 '12 at 14:43
  • 1
    Typically you'd want the try-catch right around the whole of the try-finally (and also the resource acquisition). The Execute Around Idiom is a handy way to avoid repeating this sort of thing (although it is overly verbose, probably until Java SE 8). – Tom Hawtin - tackline Apr 01 '12 at 15:05

1 Answers1

9

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140