Finally
layout: default
title: finally
A try/catch block optionally can be followed by a finally block.
- The
finallyblock executes whether or not an exception occurs.
try {
mayCrash();
System.out.println("No exception.");
}
catch (FileNotFoundException e) {
System.out.println("Exception occurred.");
}
finally {
System.out.println("mayCrash() was called.");
}
The finally block always executes, unless the JVM itself exits in the try or a catch.
try {
mayCrash();
System.out.println("No exception, returning.");
return; // Return from method....
}
catch (FileNotFoundException e) {
System.out.println("Exception occurred, returning.");
return; // Return from method....
}
finally {
// ... but execute the finally block on the way out.
System.out.println("finally block: mayCrash() was called.");
}
Exception occurred, returning.
finally block: mayCrash() was called.
A finally block comes after all catch blocks.
try {
mayCrash();
}
finally {
System.out.println("Hello from finally!");
}
catch (Exception e) { // WILL NOT COMPILE: Syntax error.
e.printStackTrace();
}
- A
trycan be followed byfinally, with nocatchblocks.
try {
System.out.println("Trying to print, then returning.");
return;
}
finally {
System.out.println("Hello from finally!");
}
Trying to print, then returning.
Hello from finally!
Drill¶
Exceptions/com.example.exceptions.drills.FinallyDrill* RunFinallyDrilland examine the stack trace. Doesmainfinish executing? * InrunMethodadd afinallyblock that usesSystem.errto print a message. RunFinallyDrillagain. Does the new message print? Doesmainfinish executing? * Inlaunch, surround the call torunMethodwith atry/catch. (Tip: in Eclipse, highlight the method call line, right-click, and choose Surround With and Try/catch block). In thecatchblock, useSystem.errto print a message, followed byreturn. Run and examine the results. * Add afinallyto thetry/catchinlaunch, which usesSystem.errto print a message, followed byreturn. Does the message print? Doesmaincomplete? * In thecatchblock inlaunch, change thereturntoSystem.exit(1). What happens when you run it?