What is the difference between throw and throws in Java?
throw is a statement that actually raises one exception object at that moment. throws is part of a method signature that warns callers which checked exceptions the method might pass on.
Explain it simply
A referee who shows a red card is doing throw: it happens right now, to a specific player. A notice on the stadium gate saying "play may be stopped for rain or injury" is throws: it declares what might happen.
Example
static void withdraw(double balance, double amount) throws Exception { // declaration
if (amount > balance) {
throw new Exception("Insufficient balance"); // action
}
System.out.println("Collect cash");
}
try {
withdraw(500, 800);
} catch (Exception e) {
System.out.println(e.getMessage()); // prints: Insufficient balance
}What to say in the interview
"throw is used inside a method body with one exception instance, for example throw new IllegalArgumentException(...). throws appears after the parameter list and can list several exception classes separated by commas. A checked exception must either be caught or declared with throws, otherwise the code will not compile. Unchecked exceptions can be thrown without any declaration."
Common mistakes
- Writing
throwsfollowed bynew Exception(). throws takes class names, throw takes an object. - Declaring
throws Exceptioneverywhere, which gives callers no useful information.