How to Use the finally Block in Java

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Finally
    A finally block is present after the catch. The statement in the block will execute whether or not an ArrayIndexOutOfBoundsException is thrown.
  2. Save your file as UsefinallyBlock.java.
  3. 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.
    Compile Source for Finally
  4. Type in the command to run your program without providing a command line parameter and hit Enter.
    Run for Finally
    The ArrayIndexOutOfBoundsException was thrown because the args array is empty. The program caught the exception and displayed an error message. Notice the output of the finally block is displayed as well.
  5. Type in the command to run your program and be sure to enter the parameter ("Stephen" in this example) and hit Enter.
    Run for Finally
    The program ended normally because the args array had one item. Again, the output of the finally block is displayed.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss