1. java-hell.de
  2. Topics
  3. Exceptions
Topic 9 of 11

Learn Java Exceptions – try, catch, finally

Programs crash – the only question is whether you're ready. You'll learn to catch exceptions with try and catch, handle different kinds of errors and clean up with finally.

The exercises

What you'll learn in this topic

  1. Program crashes
  2. Not a valid number
  3. Handling two exceptions
  4. finally — always at the end
Exercise 1 of 4

Program crashes

Sometimes things happen in your code that Java just can't handle — dividing by zero, for example.

Then Java throws an exception and your program crashes.

Catch the exception with try { ... } catch (ArithmeticException e) { ... } and print Not by zero! instead.

Starter code
void main() {
    int x = 10 / 0;
    IO.println(x);
}
Background
What is an exception?

An exception is an object Java creates when something goes wrong. Examples: dividing by 0 (ArithmeticException), accessing null (NullPointerException), an array index that's too big (ArrayIndexOutOfBoundsException).

Without try/catch, the exception travels up through the calling methods. If nobody catches it, the program dies — with a stack trace in the terminal.

With try/catch you catch the exception and can react to it, without your program crashing.

Exercise 2 of 4

Not a valid number

Integer.parseInt("abc") throws a NumberFormatException — the text isn't a number.

Catch the exception and print Not a number! instead of the value.

Starter code
void main() {
    int number = Integer.parseInt("abc");
    IO.println(number);
}
Exercise 3 of 4

Handling two exceptions

A try block can have multiple catch blocks — one per exception type.

The code in the editor accesses arr[5], but the array only has 3 elements — an ArrayIndexOutOfBoundsException.

Wrap the line in try/catch and handle both cases:

  • ArrayIndexOutOfBoundsException → print Index too big!
  • NullPointerException → print Null!
Starter code
void main() {
    int[] arr = {10, 20, 30};
    IO.println(arr[5]);
}
Background
Order of catch blocks

Java goes through the catch blocks from top to bottom and takes the first one that matches. That's why more specific exceptions must come before more general ones — otherwise the general block would grab everything (the compiler actually rejects the wrong order with an "already been caught" error).

Since Java 7 you can combine several exception types in one catch: catch (IOException | SQLException e).

Exercise 4 of 4

finally — always at the end

The finally block always runs — no matter whether an exception happened or not.

It's used, for example, to cleanly close files or connections.

Extend the code: after the catch, add a finally block that prints Done.

The output should be:

Oops!
Done.
Starter code
void main() {
    try {
        int x = 10 / 0;
    } catch (ArithmeticException e) {
        IO.println("Oops!");
    }
}
Background
When does finally run?

Always. Whether the try block ran normally, an exception was thrown (caught or not), or a return left the try/catch. The only exceptions: System.exit() or a JVM crash.

Since Java 7 there's try-with-resources: try (Scanner s = new Scanner(...)) closes things automatically — no finally needed.

Enough reading. Your turn.

In the tutorial you write the code yourself, hit Run and instantly see whether your program works. No JDK, no IDE, no bullshit.

Practice Exceptions in your browser