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
| Parameter | Type | Description |
|---|---|---|
| message | String | The error text, available via `getMessage()`. |
| cause | Throwable | Optional 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 100Notes
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
- RuntimeException — The base class of unchecked exceptions — bugs in program logic.
- throw — Throws an exception and stops the method.
- try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.
- Throwable.getMessage() — Returns the message text of an exception.
- Throwable.getCause() — Returns the original exception wrapped by the current one.
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.