Exception Handling: Finally Tutorial

This tutorial will build on concepts from my Exception Handling: Try and Catch Tutorial. At the core of exception handling there is one more code block that needs to be addressed, the finally block. The finally block is a code block that always runs regardless of any exceptions in the try block. The purpose of the finally block is to execute statements that must run because of some sort of mandatory condition. The most common use of the finally block is to close file handles that may have been opened in the try statement.
The structure looks like this:
try {
        questionableMethod();
} catch (ExceptionType varName) {
        doSomethingElse();
} finally {
        statements that always run;
}

There are certain rules that apply to the relationship between try, catch, and finally.

  • No independent statements can exist between the code blocks of a try/catch/finally statement.
  • At a minimum, a try block must have either a catch block or a finally block.
  • A finally block will execute even if there is a return statement in the try or catch block.
  • A finally block will execute if there are exceptions or no exceptions - basically all the time.
  • The only way a finally block will ever fail to execute is if program termination occurs (extremely rare).

This tutorial also includes concepts from the following tutorials:



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md TryCatchFinally
C:\Java>cd TryCatchFinally
C:\Java\TryCatchFinally>Notepad TryCatchFinally.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.io.*;

class TryCatchFinally {
    public static void main(String args[]) {
        int x = 0;
        try {
            x = 13 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Caught exception: " + e.getMessage());
        } finally {
            System.out.println("First finally just executed.\n");
        }

        try {
            String sArray[] = { "Hello", "World", "No problem here" };
            System.out.println(sArray[sArray.length - 1]);
        } finally {
            System.out.println("Second finally just executed.\n");
        }

        //new FileIntro().makeFile();

        try {
            System.out.println("Calling the return statement");
            return; // replace with System.exit(1);
        } finally {
            System.out.println("Finally evens runs after a return statement!");
        }        
    }
}

class FileIntro {
    // Demonstrate finally for closing file handles     
    void makeFile() {
        FileWriter f = null; // initialize within scope
        BufferedWriter out = null;
        try {
            f = new FileWriter("c:\\java\\Hello.txt");
            out = new BufferedWriter(f);
            out.write("Hello file maker.");
        } catch (IOException e ) {
            System.out.println("Unable to create the file: " + e.getMessage());
        } finally {
            try { out.close(); } catch (IOException e) { }
            try { f.close(); } catch (IOException e) { }
        }
    }    
}


Now switch back to the command prompt (CMD) and type in javac TryCatchFinally.java and press Enter.
Now type in java TryCatchFinally and press Enter.


C:\Java\TryCatchFinally>javac TryCatchFinally.java
C:\Java\TryCatchFinally>java TryCatchFinally
Caught exception: / by zero
First finally just executed.

No problem here
Second finally just executed.

Calling the return statement
Finally evens runs after a return statement!


Final thoughts

The finally block is a code block that always runs irregardless of any exceptions in the try block.


Tutorials