RuntimeException
The base class of unchecked exceptions — bugs in program logic.
Available since: Java 1.0
Syntax
public class RuntimeException extends Exception
public RuntimeException(String message)
public RuntimeException(String message, Throwable cause)Parameters
| Parameter | Type | Description |
|---|---|---|
| message | String | The error text. |
| cause | Throwable | Optional original cause. |
Examples
An unchecked exception needs no throws declaration:
class OrderNotFoundException extends RuntimeException {
OrderNotFoundException(int id) {
super("Order " + id + " not found");
}
}
String findOrder(int id) {
if (id != 1) throw new OrderNotFoundException(id);
return "Order 1: 2 books";
}
void main() {
IO.println(findOrder(1));
try {
findOrder(5);
} catch (OrderNotFoundException e) {
IO.println(e.getMessage());
}
}Output:
Order 1: 2 books
Order 5 not foundNotes
The compiler does not force you to catch subclasses of RuntimeException. They usually mean a programmer error: an unexpected null, a wrong index, an invalid argument. Most modern libraries use unchecked exceptions.
See also
- Exception — The base class of exceptions a program can catch and handle.
- IllegalArgumentException — Signals that a method received an invalid argument.
- IllegalStateException — Signals that a method was called at the wrong time — the object is in the wrong state.
- NullPointerException — Thrown when a method or field is accessed through a `null` reference.
Related recipes
In the tutorial
- Checked and unchecked exceptions — Checked and unchecked exceptions in Java — what the compiler requires, the throws clause, RuntimeException and wrapping exceptions.