Although throw and throws share a similar linguistic root, they perform completely different functions in Java exception handling.
| Parameter | throw |
throws |
|---|---|---|
| Purpose | Used to explicitly instantiate and throw an exception object | Used to declare that a method may cause checked exceptions |
| Location | Inside the body of a method or block | In the method header signature |
| Syntax | Followed by an exception instance (e.g. throw new MyException();) |
Followed by exception class names (e.g. throws IOException, SQLException) |
| Quantity | Throws only one exception instance at a time | Can declare multiple exception classes separated by commas |
import java.io.IOException;
public class ThrowThrowsDemo {
// Declares checked exception with 'throws'
public static void validateAge(int age) throws IOException {
if (age < 18) {
// Explicitly throws an exception object with 'throw'
throw new IOException("Access Denied: Age must be 18 or above!");
} else {
System.out.println("Access Granted: Welcome to the system.");
}
}
public static void main(String[] args) {
try {
validateAge(15); // Invocation that triggers throw
} catch (IOException e) {
System.err.println("Caught in main: " + e.getMessage());
}
}
}
Exam Question: "Are unchecked exceptions (RuntimeException) propagated automatically down the Call Stack?"
Answer: Yes! By default, all unchecked exceptions automatically propagate down the entire Call Stack without needing any throws keyword. If method m3() throws a NullPointerException, it automatically drops to caller m2(), then to caller m1(), and finally to main().
Now let us learn how to create your own custom domain-specific Exception classes. Proceed to: Java Custom Exceptions →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Catching thrown exceptions.
Throwing custom business errors.
Checked vs unchecked.
Method signatures.