Difference Between Throw and Throws
throw and throws differ by one letter and are constantly mixed up, especially in interviews. The simplest way to remember them: throw is an action ("throw this exception now"), and throws is a warning label ("this method might throw these"). One happens inside the method body; the other is written in the method's header.
Both in One Method
public class Withdraw {
static class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) { super(message); }
}
static long balance = 2000;
static void withdraw(long amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
"Navika needs Rs. " + (amount - balance) + " more");
}
balance -= amount;
System.out.println("Withdrew " + amount + ", left " + balance);
}
public static void main(String[] args) {
try {
withdraw(500);
withdraw(5000);
} catch (InsufficientFundsException e) {
System.out.println("Refused: " + e.getMessage());
}
}
}Withdrew 500, left 1500
Refused: Navika needs Rs. 3500 moreHow it works
throws InsufficientFundsExceptionin the header warns callers that this checked exception may come out.throw new InsufficientFundsException(...)in the body actually raises it when the balance is too low.maincatches it, as the warning label requires.
Side by Side
throw | throws | |
|---|---|---|
| What it is | A statement that raises an exception | A clause that declares exceptions |
| Where | Inside a method body | In the method or constructor header |
| Followed by | One exception object: throw new X(...) | One or more exception types: throws X, Y |
| How many | Exactly one exception at a time | Any number of types, comma-separated |
| Effect | Stops the method immediately | Nothing at runtime; informs the compiler and callers |
| Needed for | Raising any exception | Passing on checked exceptions |
Common Mistakes
Writing throws new X() or throw X. throw takes an object; throws takes type names.
Adding throws but never throwing. The declaration then misleads callers.
Forgetting throws for a checked exception you throw. The compiler reports "unreported exception".
Interview Corner
What is the difference between throw and throws?
throw is a statement used inside a method to raise a specific exception object, and it immediately stops the method. throws is a clause in a method signature that declares the checked exception types the method may propagate to its caller; it doesn't throw anything itself. throw takes one instance; throws lists one or more classes.
Practice
- Easy: For each line, say whether it's valid:
throw new IOException("x");,void a() throws IOException,throws new IOException();,void b() throw IOException. - Harder: Write
static int score(String text) throws InvalidScoreExceptionwith your own checked exception, throwing it for values outside 0 to 100.
Key Takeaways
Was this tutorial helpful?