-4

Consider the code

try{
    //code
} catch(Exception e) {
    // handle
} finally {
    // close open connections
}

and this

try{
    //code
} catch(Exception e) {
    // handle
}
// close open connections

since both are same what is the necessity of finally block?

3 Answers3

2

The finally block will always be executed, even if you don't catch all the exceptions thrown by the try block in the catch block, or if the catch block throws a new exception.

In the second snippet, the code following the try-catch block won't be executed if either the try or catch blocks throw exceptions not caught by the catch block.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

A finally block is much safer, as it's guaranteed to execute even if your try block throws an exception that isn't handled by the catch block or returns.

It also has the side effect of organizing all the "cleanup" code in an expected location, making the code (arguably) easier to maintain.

It's worth noting, by the way, that if you're using Java 7 or higher, and the resource you're handling is an AutoCloseable (such as a java.sql.Connection, for example), there's an even cleaner solution - the try-with-resource syntax, which saves you the hassle of explicitly closing the resource:

try (Connection con = /* something */) {
    // code
} catch (SomeException e) {
    // handle
    // If there's nothing intelligent to do, this entire clause can be omitted.
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

finally block is used to execute important code such as closing connection, stream etc. finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Java finally block is always executed whether exception is handled or not.

For each try block there can be zero or more catch blocks, but only one finally block. The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Pradeep Singh
  • 1,094
  • 1
  • 9
  • 24