JOOPs Through Java
All lessons

Unit 5 · Applying Java OOP · 10 min

Exception handling

An exception is a problem that happens while the program is running. try-catch lets you handle it instead of letting the program crash.

Why this matters

Dividing by zero or reading a missing array index will stop your program dead. Handling exceptions keeps it alive and user friendly.

Real-life analogy

A circuit breaker in your house. Instead of the whole building burning down, the breaker trips and you fix one thing.

Syntax

Syntax
try {
    // risky code
} catch (ExceptionType e) {
    // what to do when it fails
} finally {
    // normally runs after try/catch
}

Example

Java
public class Safe {
    public static void main(String[] args) {
        int[] marks = {80, 75, 90};

        try {
            System.out.println(marks[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("That subject does not exist!");
        }

        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } finally {
            System.out.println("Finally runs after try/catch");
        }

        System.out.println("Program continues normally");
    }
}

Output

That subject does not exist!
Cannot divide by zero: / by zero
Finally runs after try/catch
Program continues normally

Step by step

  1. 1`marks[5]` on an array of size 3 throws ArrayIndexOutOfBoundsException.
  2. 2The matching catch block runs instead of the program crashing.
  3. 3`10 / 0` throws ArithmeticException; e.getMessage() describes it.
  4. 4`finally` normally runs whether or not an exception happened, so it is useful for cleanup. It is not guaranteed if the JVM terminates abruptly.
  5. 5Because both problems were handled, the last line still prints.

Key points

  • Checked exceptions must be handled or declared with throws
  • Unchecked (runtime) exceptions include ArithmeticException, NullPointerException
  • throw raises an exception; throws declares that a method may raise one
  • finally normally executes after try/catch, except when the JVM terminates abruptly

Common mistakes

  • Catching Exception for everything and printing nothing
  • Catching a parent exception before a child one (unreachable catch)
  • Using exceptions for ordinary control flow

Try it yourself

  • Handle InputMismatchException when a user types text instead of a number.
  • Write a method that throws an exception when marks are above 100.
Open the practice notebook