Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
messageStringThe error text.
causeThrowableOptional 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 found

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.