AI Hints
Home›Java Tutorial›Checked and Unchecked, throw and Custom Exceptions, try-with-resources
Java · Lesson 95 of 120

throw and Custom Exceptions

Signal your own problems.

⏱ 2 min read▶ Video at 2:00:33🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Your own methods can throw exceptions too. When a method gets a value it can't work with, throwing an exception is a clear way to say so.

  • Your methods can throw
  • Bad input?
  • Say so clearly

throw

Set age checks its input. If the age is impossible, it throws a new illegal argument exception, with a helpful message. Throw stops the method straight away. Main catches it, and prints the message. Run it. Thirty is accepted. Minus four is rejected, with a clear reason.

Main.javajava
public class Main {
    static void setAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Age must be 0-150, got " + age);
        }
        System.out.println("Age set to " + age);
    }

    public static void main(String[] args) {
        setAge(30);
        try {
            setAge(-4);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
Output
Age set to 30
Rejected: Age must be 0-150, got -4

A custom exception

You can make your own exception class, by extending Exception. Its constructor builds a message, and passes it to super. The name itself explains the problem, insufficient funds.

Main.javajava
public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(double needed) {
        super("Not enough money. Short by " + needed);
    }
}

Using it

Pay declares that it throws our exception. If the amount is too much, it throws. Main catches it. Run it. Fifteen is paid, leaving five. Paying twelve is too much, and we're short by seven.

Main.javajava
public class Main {
    static double balance = 20;

    static void pay(double amount) throws InsufficientFundsException {
        if (amount > balance) throw new InsufficientFundsException(amount - balance);
        balance -= amount;
        System.out.println("Paid " + amount + ", left " + balance);
    }

    public static void main(String[] args) {
        try {
            pay(15);
            pay(12);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
Paid 15.0, left 5.0
Not enough money. Short by 7.0
Also uses InsufficientFundsException.java
public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(double needed) {
        super("Not enough money. Short by " + needed);
    }
}

Summary

Throw new, and an exception type, signals a problem. Extend Exception, to make your own, with a clear name. Next, closing files automatically.

Key takeaways
  • throw new …
  • extends Exception
  • Clear names
Next up: try-with-resources — close things automatically