Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

throw — explicit exception raising

throw — explicit exception raising: A throw statement evaluates a Throwable expression and completes abruptly, passing the exception to the nearest compatible catch or caller.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

throw

A throw statement evaluates a Throwable expression and completes abruptly, passing the exception to the nearest compatible catch or caller.

Throw a specific domain exception with its cause when a contract cannot be met; declare a checked exception with throws or handle it.

Do not use exceptions for routine control flow, discard the cause when wrapping, or catch broadly merely to rethrow without information.

throw null causes NullPointerException; the throw statement differs from a throws clause, while precise rethrow can narrow a checked type.

Value -2 triggers throw with message negative:-2, the catch prints it, and valid value 3 returns normally.

Examples

public class Main {
    static int requireNonNegative(int value) {
        if (value < 0) throw new IllegalArgumentException("negative:" + value);
        return value;
    }

    public static void main(String[] args) {
        try {
            requireNonNegative(-2);
        } catch (IllegalArgumentException exception) {
            System.out.println(exception.getMessage());
        }
        System.out.println(requireNonNegative(3));
    }
}

Result

negative:-2
3

Value -2 triggers throw with message negative:-2, the catch prints it, and valid value 3 returns normally.

Sources