throw, throws and Your Own Exceptions

Throwing an exception yourself

Your own methods can refuse bad values by throwing an exception with throw:

public class Main {
    static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age can't be negative: " + age);
        }
        System.out.println("Age set to " + age);
    }

    public static void main(String[] args) {
        setAge(25);
        try {
            setAge(-3);
        } catch (IllegalArgumentException e) {
            System.out.println("Problem: " + e.getMessage());
        }
    }
}

Output

Age set to 25
Problem: Age can't be negative: -3

Checked and unchecked exceptions

  • Unchecked exceptions (children of RuntimeException) are usually programming mistakes, like a null variable. Java doesn't force you to catch them.
  • Checked exceptions (other children of Exception) are problems you should expect, like a missing file. Java forces you to either catch them, or warn callers with throws.
class TooColdException extends Exception {
    TooColdException(String message) {
        super(message);
    }
}

public class Main {
    static void swim(int waterTemp) throws TooColdException {
        if (waterTemp < 18) {
            throw new TooColdException("Water is only " + waterTemp + " degrees");
        }
        System.out.println("Splash! Enjoy your swim.");
    }

    public static void main(String[] args) {
        int[] temps = {25, 12};
        for (int t : temps) {
            try {
                swim(t);
            } catch (TooColdException e) {
                System.out.println("No swimming: " + e.getMessage());
            }
        }
    }
}

Output

Splash! Enjoy your swim.
No swimming: Water is only 12 degrees

TooColdException is our own exception: just a class that extends Exception. Because it's checked, swim must say throws TooColdException, and the caller must handle it. Forget, and the compiler complains:

class TooColdException extends Exception {
}

public class Main {
    static void swim() {
        throw new TooColdException();
    }

    public static void main(String[] args) {
        swim();
    }
}

Output (the program does not compile)

Main.java:6: error: unreported exception TooColdException; must be caught or declared to be thrown
        throw new TooColdException();
        ^

Remember: throw (no s) throws an exception right now. throws (with s) in a method header warns that the method might throw one.

HOME LABS COMMUNITY DASHBOARD