Java Throw Keyword

Naveen AnamaneniUpdated · 4 min read

So far, exceptions came from Java itself: parseInt threw on bad text, division threw on zero. Your own methods have rules too. A bank account shouldn't accept a negative deposit; an age can't be 250. When a rule is broken, your method should refuse loudly instead of carrying on with nonsense. The throw keyword lets you do that: create an exception object and throw it, exactly like Java does.

Refusing Bad Input

Deposits.java▶ Try it
public class Deposits {
    static long balance = 1000;
 
    static void deposit(long amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException(
                "Deposit must be positive, got " + amount);
        }
        balance += amount;
        System.out.println("Deposited " + amount + ", balance " + balance);
    }
 
    public static void main(String[] args) {
        deposit(500);
        try {
            deposit(-200);
        } catch (IllegalArgumentException e) {
            System.out.println("Refused: " + e.getMessage());
        }
        System.out.println("Final balance " + balance);
    }
}
Output
Deposited 500, balance 1500
Refused: Deposit must be positive, got -200
Final balance 1500

How it works

  1. throw new IllegalArgumentException("...") creates an exception object with a message and throws it.
  2. The method stops immediately: balance += amount never runs for the bad deposit, so the balance stays correct.
  3. The caller catches it like any other exception.

Choosing the Exception Type

Use a standard exception when one fits; it tells readers the kind of problem at a glance.

SituationThrow
A method argument is invalidIllegalArgumentException
A required argument is nullNullPointerException (via Objects.requireNonNull)
The object isn't in a state to do this nowIllegalStateException
The operation isn't supportedUnsupportedOperationException
An index is out of rangeIndexOutOfBoundsException
A domain-specific problem the caller should handleYour own exception (see "Custom Exceptions in Java")

The Rules of throw

Compiler output: three throw mistakes
ThrowErr.java:3: error: unreported exception Exception; must be caught or declared to be thrown
        if (age < 0) throw new Exception("negative age");
                     ^
ThrowStr.java:2: error: incompatible types: String cannot be converted to Throwable
    static void check() { throw "bad"; }
                          ^
After.java:4: error: unreachable statement
        System.out.println("never");
        ^
  1. Throwing a checked exception follows the catch-or-declare rule: the method needs throws Exception or a try around it.
  2. Only Throwable objects can be thrown, not strings or numbers.
  3. Code right after a throw can never run, so the compiler rejects it.

Rethrowing

Sometimes you want to do something with an exception, like logging it, and then let it continue to the caller. Just throw it again from the catch:

Rethrow.java▶ Try it
public class Rethrow {
    static int parse(String text) {
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            System.out.println("log: bad number from Srihitha: " + text);
            throw e;
        }
    }
 
    public static void main(String[] args) {
        try {
            parse("4x");
        } catch (NumberFormatException e) {
            System.out.println("main also sees: " + e.getMessage());
        }
    }
}
Output
log: bad number from Srihitha: 4x
main also sees: For input string: "4x"

Common Mistakes

Throwing after changing state. Validate first, then change fields, so a refused call leaves the object untouched.

Throwing plain Exception or RuntimeException. Pick a specific type.

Messages without the bad value. Include it, unless it's secret, like a password.

Interview Corner

What does the throw keyword do?

throw explicitly throws an exception object, an instance of Throwable, from the current point. Execution of the current method stops and the exception propagates to the caller until a matching catch handles it. Throwing a checked exception requires the method to catch it or declare it with throws.

Practice

  1. Easy: Write static void setAge(int age) that throws IllegalArgumentException for ages below 0 or above 150, with a clear message.
  2. Harder: Write a Ticket class with a cancel() method that throws IllegalStateException if the ticket is already canceled. Test both cases.

Quick check: throw

4 questions
1What does throw do to the current method?
2Which exception fits a negative deposit amount?
3Can you write throw "error";?
4When should you validate an argument?

Key Takeaways

Was this tutorial helpful?

Lesson 226 of 482