Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 13 of 20 · 5 min read

Java exception handling

Java exception handling notes with examples: try, catch and finally, checked and unchecked exceptions, throw, throws, try-with-resources and custom exceptions.

What is an exception?

An exception is an error that happens while the program runs: dividing by zero, reading a file that does not exist, typing letters where a number was expected. If nothing handles it, the program stops and prints a stack trace.

int a = 10, b = 0;
System.out.println(a / b);   // ArithmeticException: / by zero
System.out.println("never printed");

Exception handling lets the program react sensibly and carry on.

try and catch

try {
    int result = 10 / 0;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
System.out.println("Program continues");
  • Code that might fail goes in try.
  • If an exception is thrown, Java jumps to the matching catch. The rest of the try block is skipped.
  • If no exception is thrown, the catch is skipped.

Several catch blocks

import java.util.Scanner;
import java.util.InputMismatchException;

Scanner sc = new Scanner(System.in);
int[] marks = {70, 80, 90};
try {
    int i = sc.nextInt();
    System.out.println(marks[i]);
} catch (InputMismatchException e) {
    System.out.println("Please type a number");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Choose 0, 1 or 2");
} catch (Exception e) {
    System.out.println("Something went wrong: " + e.getMessage());
}

Put specific exceptions first and the general Exception last; otherwise the compiler reports that the later catch is unreachable.

Since Java 7, one catch can handle several types: catch (IOException | NumberFormatException e).

finally

A finally block runs whether or not an exception happened, even after a return. Use it for clean-up such as closing a file or a database connection.

try {
    System.out.println("Opening");
    int x = 5 / 0;
} catch (ArithmeticException e) {
    System.out.println("Caught");
} finally {
    System.out.println("Closing");
}
Opening
Caught
Closing

The exception family

Throwable
  Error                 serious JVM problems: OutOfMemoryError, StackOverflowError (do not catch)
  Exception
    IOException, SQLException, ...            checked
    RuntimeException                          unchecked
      ArithmeticException, NullPointerException,
      ArrayIndexOutOfBoundsException, NumberFormatException,
      IllegalArgumentException, ClassCastException

Checked versus unchecked

CheckedUnchecked
ExtendsException (not RuntimeException)RuntimeException
Compiler forces you to handle it?yesno
Usually caused bythe outside world: files, network, databasebugs in the code
ExamplesIOException, SQLExceptionNullPointerException, ArithmeticException

For a checked exception you must either catch it or declare it with throws.

throw and throws

  • throw raises an exception yourself.
  • throws in a method header warns callers that the method may throw a checked exception.
static void withdraw(double balance, double amount) {
    if (amount > balance) {
        throw new IllegalArgumentException("Insufficient balance");
    }
    System.out.println("Withdrawn " + amount);
}

static String firstLine(String path) throws java.io.IOException {
    return java.nio.file.Files.readAllLines(java.nio.file.Path.of(path)).get(0);
}

try-with-resources

Objects such as files, scanners and database connections must be closed. In a try-with-resources statement Java closes them automatically, even if an exception is thrown:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader br = new BufferedReader(new FileReader("marks.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Could not read the file: " + e.getMessage());
}

Any class that implements AutoCloseable can be used this way.

Custom exceptions

Create your own exception class to describe a problem in your program's own words:

class InsufficientFundsException extends Exception {
    InsufficientFundsException(String message) {
        super(message);
    }
}

class Account {
    private double balance = 1000;

    void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Need " + (amount - balance) + " more");
        }
        balance -= amount;
    }
}
try {
    new Account().withdraw(1500);
} catch (InsufficientFundsException e) {
    System.out.println(e.getMessage());   // Need 500.0 more
}

Extend Exception for a checked exception, or RuntimeException for an unchecked one.

Useful methods on an exception

  • e.getMessage(): the message text.
  • e.toString(): class name plus message.
  • e.printStackTrace(): the full trace, for debugging.

Common mistakes

  • Catching Exception first, which hides the specific catches below it.
  • An empty catch { } that silently swallows errors.
  • Confusing throw (do it now) with throws (may happen, declared in the header).
  • Forgetting to close resources; use try-with-resources.
  • Catching exceptions to hide bugs such as NullPointerException instead of fixing the code.

Key points

  • try holds risky code, catch handles a specific exception, finally always runs.
  • Checked exceptions must be caught or declared with throws; unchecked ones (RuntimeException) need not be.
  • throw new XyzException("msg") raises an exception.
  • try-with-resources closes files and connections automatically.
  • Custom exceptions extend Exception or RuntimeException.

Practice questions

1. What is printed?
try {
    System.out.print("A");
    int[] a = new int[2];
    a[5] = 1;
    System.out.print("B");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.print("C");
} finally {
    System.out.print("D");
}

ACD. The exception skips B; the catch prints C and finally prints D.

2. Is NumberFormatException checked or unchecked?

Unchecked: it extends IllegalArgumentException, which extends RuntimeException.

3. Read a number as text and print a friendly message if it is not a number.
String text = "12a";
try {
    int n = Integer.parseInt(text);
    System.out.println(n * 2);
} catch (NumberFormatException e) {
    System.out.println("'" + text + "' is not a whole number");
}
4. Write a custom unchecked exception InvalidMarksException and throw it when marks are above 100.
class InvalidMarksException extends RuntimeException {
    InvalidMarksException(String msg) { super(msg); }
}

static void check(int marks) {
    if (marks > 100) throw new InvalidMarksException("Marks above 100: " + marks);
}
5. Why is try-with-resources better than closing a file in finally by hand?

It closes the resource automatically, in the right order, even when an exception is thrown, and needs less code, so it is harder to forget or get wrong.