AI Hints
Home›Java Tutorial›What Exceptions Are, try and catch, and finally
Java · Lesson 93 of 120

finally

Always runs.

⏱ 2 min read▶ Video at 1:58:08🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Some code must run no matter what. Closing a file, or a connection. A finally block always runs, whether an exception happened, or not.

  • Must always run
  • Error or no error
  • finally

finally always runs

The finally block comes after try and catch. First, ten divided by two works fine. Then ten divided by zero throws, and catch handles it. Either way, the finally block runs. Run it. Closing the calculator prints both times.

Main.javajava
public class Main {
    static void divide(int a, int b) {
        System.out.println("Opening the calculator");
        try {
            System.out.println(a + " / " + b + " = " + (a / b));
        } catch (ArithmeticException e) {
            System.out.println("Can't divide by zero");
        } finally {
            System.out.println("Closing the calculator");
        }
    }

    public static void main(String[] args) {
        divide(10, 2);
        System.out.println("---");
        divide(10, 0);
    }
}
Output
Opening the calculator
10 / 2 = 5
Closing the calculator
---
Opening the calculator
Can't divide by zero
Closing the calculator

The order

Java runs the try block. If something throws, it jumps to the matching catch. Then, in every case, it runs finally. Only after that does it carry on.

  1. try
  2. catch (if thrown)
  3. finally (always)
  4. carry on

Summary

Finally runs whether or not an exception happens. Use it for clean up. Next, two families of exceptions.

Key takeaways
  • try / catch / finally
  • finally always runs
  • Clean-up code
Next up: Checked and Unchecked — two families of exceptions