O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Finally

The finally keyword is used after a try/catch block to indicate that the code inside the finally block should be executed whether the code inside the try block generates an exception or not. No matter what happens (unless someone pulls the plug on your box or externally kills your JVM process), the code in your finally block will run.

Do it like this:

try {
...
} catch (SomeEx se) {
 ...
} finally {
 //put the code you want to run to matter what here.
}

Note that although the preceding code is how you will see it used 99% of the time, you can use the finally block without a catch block.

The finally statement is very useful, especially for doing complex operations involving files, a database, or a network connection, because there ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required