Custom Exceptions and throws

Make your own exception type, throw it when a rule is broken, and make callers handle it with throws.

Java · beginner · 8 min · 15 steps · free

What you'll learn

CustomExceptionDemo.java

class InsufficientFundsException extends Exception {
    InsufficientFundsException(String message) {
        super(message);
    }
}

public class CustomExceptionDemo {
    static double withdraw(double balance, double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Need " + (amount - balance) + " more");
        }
        return balance - amount;
    }

    public static void main(String[] args) {
        double balance = 100;
        try {
            balance = withdraw(balance, 30);
            balance = withdraw(balance, 500);
        } catch (InsufficientFundsException e) {
            System.out.println("Refused: " + e.getMessage());
        }
        System.out.println("Balance: " + balance);
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). balance is created on the stack with the value 100.
  2. Withdraw 30 from 100: allowed.
  3. Java checks amount > balance to decide which way the code goes.
  4. withdraw() has finished, so its variables are gone.
  5. The value it returned, 70, is stored in balance.
  6. Java calls withdraw(), with balance = 70 and amount = 500. It gets its own variables on the stack.
  7. 500 > 70: not enough money.
  8. throw creates our exception with a message and sends it up to the caller.
  9. backtrace in the InsufficientFundsException object changes from null to an Object[]. detailMessage in the InsufficientFundsException object changes from null to "Need 430.0 more". cause in the InsufficientFundsException object changes from null to an InsufficientFundsException. stackTrace in the InsufficientFundsException object changes from null to a StackTraceElement[].
  10. InsufficientFundsException() has finished, so its variables are gone.
  11. withdraw() has finished, so its variables are gone.
  12. The catch in main handles it.
  13. e goes out of scope and disappears. It prints Refused: Need 430.0 more.
  14. It prints Balance: 70.0.
  15. Balance stays 70.0, and the user is told why: "Need 430.0 more".

Common mistakes

Best practices

Key takeaways

Check yourself

Which is unchecked?

Answer: A class extending RuntimeException. RuntimeException subclasses need no throws.

What does throws X on a method mean?

Answer: It may throw X, and callers must deal with it. It is a warning in the signature.

More in Exception Handling