00:00

throw Keyword in Java – Explained with Examples

Last updated: 6 min read

The throw keyword lets your own code raise an exception. When a method detects a situation it cannot or should not handle, such as an invalid argument, an impossible state or a failed operation, it creates an exception object and throws it. Control leaves the method immediately and passes to the nearest matching catch block.

This tutorial covers the syntax, throwing unchecked and checked exceptions, the standard exceptions to use for validation, rethrowing and wrapping exceptions, and the rules of throw.

1. Syntax

throw syntax
throw throwableObject;

throw new IllegalArgumentException("quantity must be positive");

The expression after throw must be an object of Throwable or a subclass. You usually create it right there with new and a helpful message.

2. Throwing an Unchecked Exception

ThrowBasics.java
public class ThrowBasics {
    static void setAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Age must be between 0 and 150, got " + age);
        }
        System.out.println("Age set to " + age);
    }

    public static void main(String[] args) {
        setAge(34);
        try {
            setAge(-5);
            System.out.println("not printed");
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
Output
Age set to 34
Rejected: Age must be between 0 and 150, got -5

The statement after setAge(-5) never ran: as soon as an exception is thrown, the rest of the method and the rest of the try block are skipped.

3. Throwing a Checked Exception

If you throw a checked exception, the method must declare it with throws (or catch it itself), and callers must handle it:

ThrowChecked.java
import java.io.FileNotFoundException;

public class ThrowChecked {
    // Throwing a checked exception requires a throws clause
    static String loadTemplate(String name) throws FileNotFoundException {
        if (!name.endsWith(".html")) {
            throw new FileNotFoundException("No template named " + name);
        }
        return "<h1>" + name + "</h1>";
    }

    public static void main(String[] args) {
        for (String n : new String[] {"home.html", "home.txt"}) {
            try {
                System.out.println(loadTemplate(n));
            } catch (FileNotFoundException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
}
Output
<h1>home.html</h1>
Error: No template named home.txt

Unchecked exceptions (RuntimeException subclasses) need no declaration. See throws keyword and throw vs throws.

4. Validating Arguments and State

Most throw statements in real code protect a method from bad input or misuse. The JDK's standard exceptions describe these problems clearly:

ValidationHelpers.java
import java.util.Objects;

public class ValidationHelpers {
    static final class Order {
        private final String customer;
        private final int quantity;
        private boolean shipped;

        Order(String customer, int quantity) {
            this.customer = Objects.requireNonNull(customer, "customer must not be null");
            if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive");
            this.quantity = quantity;
        }

        void ship() {
            if (shipped) throw new IllegalStateException("order already shipped");
            shipped = true;
            System.out.println("Shipped " + quantity + " item(s) to " + customer);
        }
    }

    public static void main(String[] args) {
        Order o = new Order("Asha", 2);
        o.ship();
        try { o.ship(); } catch (IllegalStateException e) { System.out.println("IllegalStateException: " + e.getMessage()); }
        try { new Order(null, 1); } catch (NullPointerException e) { System.out.println("NullPointerException: " + e.getMessage()); }
        try { new Order("Ravi", 0); } catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException: " + e.getMessage()); }
    }
}
Output
Shipped 2 item(s) to Asha
IllegalStateException: order already shipped
NullPointerException: customer must not be null
IllegalArgumentException: quantity must be positive
ExceptionThrow it when…
IllegalArgumentExceptionAn argument has an invalid value
NullPointerExceptionAn argument is null but must not be (use Objects.requireNonNull)
IllegalStateExceptionThe object is not in the right state for this call
IndexOutOfBoundsExceptionAn index is outside the valid range (see Objects.checkIndex)
UnsupportedOperationExceptionThe operation is not supported by this object
A custom exceptionA business rule is broken, for example insufficient balance

5. Rethrowing and Wrapping

A catch block can throw too. Wrapping a low-level exception in one that makes sense to callers, while keeping the original as its cause, is a common and useful pattern:

RethrowWrap.java
public class RethrowWrap {
    static class PaymentException extends Exception {
        PaymentException(String message, Throwable cause) { super(message, cause); }
    }

    static int parseAmount(String text) {
        return Integer.parseInt(text);
    }

    static void pay(String amountText) throws PaymentException {
        try {
            int amount = parseAmount(amountText);
            System.out.println("Paid " + amount);
        } catch (NumberFormatException e) {
            throw new PaymentException("Payment failed for amount '" + amountText + "'", e);   // wrap with cause
        }
    }

    public static void main(String[] args) {
        try {
            pay("500");
            pay("5O0");
        } catch (PaymentException e) {
            System.out.println(e.getMessage());
            System.out.println("cause: " + e.getCause());
        }
    }
}
Output
Paid 500
Payment failed for amount '5O0'
cause: java.lang.NumberFormatException: For input string: "5O0"

To rethrow the same exception unchanged, simply write throw e; inside the catch block, for example after logging it.

6. Rules of throw

  • Only Throwable objects can be thrown; throw "error"; does not compile.
  • Throwing a checked exception requires catching it or declaring it with throws.
  • Statements directly after throw in the same block are unreachable and do not compile.
  • Throwing null compiles but throws a NullPointerException instead.
  • One throw statement throws exactly one exception.
  • Since Java 14, throw can be used inside switch expression branches: default -> throw new IllegalArgumentException(...);.

7. Best Practices

  • Throw early, at the point where the problem is detected.
  • Write messages that include the bad value and what was expected.
  • Prefer standard exceptions when they fit; create custom ones for domain problems.
  • Always pass the original exception as the cause when wrapping.
  • Do not throw generic Exception or RuntimeException; be specific.
  • Document thrown exceptions with Javadoc @throws tags.

8. Summary

  • throw raises an exception object and immediately leaves the current block.
  • Checked exceptions must be declared with throws or caught; unchecked ones need not be.
  • Use standard exceptions such as IllegalArgumentException and IllegalStateException for validation.
  • Rethrow or wrap exceptions in catch blocks, keeping the cause.

Related Tutorials