How to Use the finally Block in Java
See Java: Tips and Tricks for similar articles.
The finally block is coded after a try catch block. The statements in the finally block are executed unconditionally, i.e., regardless of whether an exception was thrown. To learn how to use the finally block in Java, follow these five steps.
- Open your text editor and type in the following Java statements:
A finallyblock is present after thecatch. The statement in the block will execute whether or not anArrayIndexOutOfBoundsExceptionis thrown. - Save your file as UsefinallyBlock.java.
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.

- Type in the command to run your program without providing a command line parameter and hit Enter.
The ArrayIndexOutOfBoundsExceptionwas thrown because theargsarray is empty. The program caught the exception and displayed an error message. Notice the output of thefinallyblock is displayed as well. - Type in the command to run your program and be sure to enter the parameter ("Stephen" in this example) and hit Enter.
The program ended normally because the argsarray had one item. Again, the output of thefinallyblock is displayed.
