public class ThrowVsThrows {
// Method declares that it might throw an exception
static void checkAge(int age) throws IllegalArgumentException {
if (age < 18) {
// Actually throwing the exception
throw new IllegalArgumentException("Age must be 18 or above.");
[Link]("Valid age: " + age);
public static void main(String[] args) {
try {
checkAge(15); // Will throw exception
catch (IllegalArgumentException e) {
[Link]("Exception caught: " + [Link]());
}
2) class ThrowVsThrows {
static void checkAge(int age) throws IllegalArgumentException { // "throws" =
declaration
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above."); // "throw" = action
[Link]("Valid age: " + age);
public static void main(String[] args) {
try {
checkAge(15); // will cause exception
} catch (IllegalArgumentException e) {
[Link]("Caught Exception: " + [Link]());
┌────────────────────────────────────────────────────
─────┐
│ Caller (main method) must handle it: │
│ - with try/catch block │
│ - OR declare again using "throws" │
└────────────────────────────────────────────────────
─────┘