Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

throw

Throws an exception and stops the method.

Available since: Java 1.0

Syntax

throw new ExceptionType(message);

Examples

Validating an argument:

void withdraw(double amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("Amount must be positive: " + amount);
    }
    IO.println("Withdrawn " + amount);
}
 
void main() {
    withdraw(50);
    try {
        withdraw(-5);
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}

Output:

Withdrawn 50.0
Amount must be positive: -5.0

Notes

Invalid arguments usually get IllegalArgumentException, an invalid object state IllegalStateException, an unsupported operation UnsupportedOperationException. Do not confuse throw (throw now) with throws (a declaration in the method signature).

See also

  • throws — Declares which checked exceptions a method may throw.
  • try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.
  • Objects.requireNonNull() — Checks that a value is not null and throws NullPointerException with a clear message right away.
  • IllegalArgumentException — Signals that a method received an invalid argument.

Related recipes

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.