throw and throws

Difference

throwthrows
Whatstatement that raises an exception nowpart of a method signature
Whereinside a method bodyafter the parameter list
Followed byone exception object: throw new X("msg")one or more exception types
Purposesignal a problemwarn callers what may be thrown

Validating Input

Example

public class Main {
    static void setAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Invalid age: " + age);
        }
        System.out.println("Age set to " + age);
    }

    static void sleepBriefly() throws InterruptedException {
        Thread.sleep(10);
        System.out.println("Woke up");
    }

    public static void main(String[] args) throws InterruptedException {
        setAge(25);
        try {
            setAge(-4);
        } catch (IllegalArgumentException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        sleepBriefly();
    }
}

Output

Age set to 25
Caught: Invalid age: -4
Woke up

Rethrowing and Exception Chaining

Example

Wrap a low-level exception in a higher-level one and keep the original as the cause. Never lose the cause; it is the most useful part of a stack trace.

public class Main {
    static int loadPort(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new IllegalStateException("Invalid server port in config", e);
        }
    }

    public static void main(String[] args) {
        try {
            loadPort("80a");
        } catch (IllegalStateException e) {
            System.out.println("Error : " + e.getMessage());
            System.out.println("Cause : " + e.getCause());
        }
    }
}

Output

Error : Invalid server port in config
Cause : java.lang.NumberFormatException: For input string: "80a"