Skip to lesson

With throw, your own code can throw an exception when a value is wrong, such as a negative age or a withdrawal above the balance. The caller can then catch it like any other exception.

throw: report a bad value

throw is used to explicitly throw a single exception. Without a check, withdraw(3000, 4000) quietly returns a balance of -1000. Instead, throw an exception: the method stops at that line, and the caller learns that something went wrong.

Syntax
throw new ExceptionType("message");

Example 1 · ATM: amount more than balance

Atm.javaJava
public class Atm {    static int withdraw(int balance, int amount) {        if (amount > balance) {            throw new IllegalArgumentException("Not enough balance");        }        return balance - amount;    }
    public static void main(String[] args) {        try {            System.out.println("Balance: " + withdraw(5000, 2000));            System.out.println("Balance: " + withdraw(3000, 4000));        } catch (IllegalArgumentException e) {            System.out.println("Failed: " + e.getMessage());        }    }}
Output
Balance: 3000
Failed: Not enough balance

What this code does

  • new IllegalArgumentException("Not enough balance") makes the exception, and the text becomes its message. IllegalArgumentException is the usual type for "this value is not allowed".
  • For ₹4000, throw stops withdraw at once, so return balance - amount never runs.
  • main catches it like any other exception, and getMessage() gives back the text.

If nobody catches it

An exception you throw works exactly like one Java throws. If no caller catches it, the program stops with a stack trace, and your own message is in it.

Example 2 · Nobody catches it

AgeCheck.javaJava
public class AgeCheck {    static void checkAge(int age) {        if (age < 0) {            throw new IllegalArgumentException("Age cannot be negative: " + age);        }        System.out.println("Age OK: " + age);    }
    public static void main(String[] args) {        checkAge(19);        checkAge(-5);    }}
Sample output
Age OK: 19
Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative: -5
	at AgeCheck.checkAge(AgeCheck.java:4)
	at AgeCheck.main(AgeCheck.java:11)

What this code does

  • Your own message is the message in the stack trace, so the report explains itself.
  • The throw is on line 4, and main called the method on line 11.

The exception family

Every problem Java can throw belongs to one family under Throwable, split into two groups: Error and Exception. Every exception in this module so far is a RuntimeException, one kind of Exception.

An Error is a serious problem inside Java itself, like StackOverflowError from a method that calls itself forever (see Recursion basics (opens in a new tab)) or OutOfMemoryError. Programs do not catch these.

The exceptions Java already gives you, like ArithmeticException, NullPointerException and IllegalArgumentException, are called built-in exceptions. Exception classes you write yourself, like InsufficientBalanceException, are called user-defined (or custom) exceptions. Making one needs extends, so you will write your own in Your own exception classes (opens in a new tab); for now, throw the built-in ones.

Throwable is at the top, with two groups under it. Error: serious problems such as StackOverflowError and OutOfMemoryError. Exception: checked exceptions such as FileNotFoundException. Under Exception is RuntimeException: unchecked exceptions such as ArithmeticException and NullPointerException.

Checked exceptions and throws

Some exceptions, like FileNotFoundException for a missing file, are checked: javac makes you catch them or declare them. The throws keyword is used in a method declaration to indicate that the method may throw one or more exceptions.

Example 3 · throws for a checked exception

PinCheck.javaJava
public class PinCheck {    static void checkPin(int pin) throws Exception {        if (pin != 4321) {            throw new Exception("Wrong PIN");        }        System.out.println("PIN accepted");    }
    public static void main(String[] args) {        try {            checkPin(4321);            checkPin(1111);        } catch (Exception e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
PIN accepted
Error: Wrong PIN

What this code does

  • Exception itself is checked, so checkPin must say throws Exception in its first line.
  • Because of throws, every caller must handle it. Without the try-catch in main, javac stops with unreported exception Exception; must be caught or declared to be thrown.

Unchecked exceptions are RuntimeException and its kinds: every exception you met before this lesson. They come from wrong values, so Java does not force you to catch or declare them. In short: throw (inside the method body) throws one exception now; throws (in the method's declaration) only warns that one or more may come.

Classify

Checked, unchecked or Error?

Tap a type, then tap its group.

Next step

Check your understanding

9 quick questions