Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Exception

The base class of exceptions a program can catch and handle.

Available since: Java 1.0

Syntax

public class Exception extends Throwable
public Exception(String message)
public Exception(String message, Throwable cause)

Parameters

ParameterTypeDescription
messageStringThe error text, available via `getMessage()`.
causeThrowableOptional original cause.

Examples

A custom checked exception:

class InsufficientFundsException extends Exception {
    InsufficientFundsException(String message) {
        super(message);
    }
}
 
void withdraw(int balance, int amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException("Need " + amount + ", have " + balance);
    }
    IO.println("Withdrawn " + amount);
}
 
void main() {
    try {
        withdraw(100, 30);
        withdraw(100, 250);
    } catch (InsufficientFundsException e) {
        IO.println("Error: " + e.getMessage());
    }
}

Output:

Withdrawn 30
Error: Need 250, have 100

Notes

Subclasses of Exception (except RuntimeException) are checked exceptions: the compiler requires you to either catch them or declare them in throws. Otherwise you get the compile error unreported exception ... must be caught or declared to be thrown. Catching Exception itself catches almost everything — do it only at the top level of a program.

See also

In the tutorial

  • What exceptions are — Exceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.

Thanks for reading!

Donate to the site — we work hard for you.