Java Throw Keyword
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
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);
}
}Deposited 500, balance 1500
Refused: Deposit must be positive, got -200
Final balance 1500How it works
throw new IllegalArgumentException("...")creates an exception object with a message and throws it.- The method stops immediately:
balance += amountnever runs for the bad deposit, so the balance stays correct. - 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.
| Situation | Throw |
|---|---|
| A method argument is invalid | IllegalArgumentException |
A required argument is null | NullPointerException (via Objects.requireNonNull) |
| The object isn't in a state to do this now | IllegalStateException |
| The operation isn't supported | UnsupportedOperationException |
| An index is out of range | IndexOutOfBoundsException |
| A domain-specific problem the caller should handle | Your own exception (see "Custom Exceptions in Java") |
The Rules of throw
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");
^- Throwing a checked exception follows the catch-or-declare rule: the method needs
throws Exceptionor atryaround it. - Only
Throwableobjects can be thrown, not strings or numbers. - Code right after a
throwcan 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:
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());
}
}
}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
- Easy: Write
static void setAge(int age)that throwsIllegalArgumentExceptionfor ages below 0 or above 150, with a clear message. - Harder: Write a
Ticketclass with acancel()method that throwsIllegalStateExceptionif the ticket is already canceled. Test both cases.
Key Takeaways
Was this tutorial helpful?