Start learning free

LESSON 47 OF 68 · OBJECT-ORIENTED PROGRAMMING

Raising Errors in Java: throw, try and catch

Lesson Read the full explanation

TL ; DR:

When a method can't do what it was asked, it throws an exception. The code that called it catches the exception with try and catch.


public void spend(int amount) {
    if (amount > money) {
        throw new IllegalArgumentException("not enough money");
    }

    money -= amount;
}

try {
    wallet.spend(80);
} catch (IllegalArgumentException e) {
    System.out.println("error: " + e.getMessage());
}


Full lesson:

Some requests can't be done. A wallet with 50 can't spend 80.

The method could return a special value, like -1. But the caller may forget to check it. Then the program goes on with a wrong number.

An exception is better. It is an error that the program can't miss.

Throwing an exception

  • throw new IllegalArgumentException("not enough money") stops the method at once.
  • The lines after it don't run. So the wallet keeps its money.
  • IllegalArgumentException is Java's built-in exception for a bad argument.
  • The text in the parentheses is the exception's message.
  • Some exceptions must be listed after throws in the method's header. This one doesn't need that.

Catching it

  • Put the call inside a try block.
  • When the call throws, the rest of the try block is skipped.
  • The catch block for that exception runs instead. e is the exception.
  • e.getMessage() returns its message.
  • Then the program goes on below the catch block.

An exception that nobody catches stops the whole program. Java prints it and the line where it happened.


Your task

A Wallet starts with 50. Its spend method takes money out and returns what is left.

  • In spend, throw an IllegalArgumentException when amount is more than money. Its message is "not enough money".
  • In the loop, call spend inside a try block. Print what was spent and what is left.
  • Catch the exception. Print error: and its message.

The loop tries to spend 20, then 40, then 30.

Expected output:

spent 20, 30 left
error: not enough money
spent 30, 0 left
STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · OBJECT-ORIENTED PROGRAMMING

    Raising Errors in Java, explained

    When a method can't do its job

    Some requests can't be done. A wallet holding 50 can't spend 80. The method could return a special value such as -1, but the caller may forget to check it, and the program carries on with a wrong number. An exception is an error the program can't miss: it stops the method at once and travels up to whichever code is ready to deal with it.

    Throwing

    throw new IllegalArgumentException("not enough money") creates an exception object and throws it. IllegalArgumentException is Java's built-in exception for a bad argument, and the text in the parentheses is its message. Three things follow:

    • The method stops at the throw. The lines below it don't run, so a check placed at the top protects everything after it.
    • This exception is unchecked, so the method's header needs no throws clause.
    • If nobody catches it, the exception ends the whole program, and Java prints the exception with its message and the line where it happened.

    Catching

    Put the risky call inside a try block. When the call throws, the rest of the try block is skipped and the matching catch block runs, with the exception named in the parentheses. e.getMessage() returns the message. After the catch block, the program continues normally.

    The solution in Java

    class Wallet {
        public int money;
    
        public Wallet(int money) {
            this.money = money;
        }
    
        public int spend(int amount) {
            if (amount > money) {
                throw new IllegalArgumentException("not enough money");
            }
            money -= amount;
            return money;
        }
    }
    
    class Solution {
        public void mainFunction() {
            Wallet wallet = new Wallet(50);
            int[] amounts = {20, 40, 30};
            for (int amount : amounts) {
                try {
                    int left = wallet.spend(amount);
                    System.out.println("spent " + amount + ", " + left + " left");
                } catch (IllegalArgumentException e) {
                    System.out.println("error: " + e.getMessage());
                }
            }
        }
    }
    

    The output is:

    spent 20, 30 left
    error: not enough money
    spent 30, 0 left
    

    Step by step

    1. Guard spend. At the top, an if for amount > money throws the exception with the message "not enough money".
    2. Wrap the call. In the loop, open a try block, call wallet.spend(amount), keep the result in left and print it with the amount. If the call throws, the println below it is skipped.
    3. Add the catch. It names IllegalArgumentException e and prints "error: " followed by e.getMessage().

    Follow the run: the wallet starts with 50. Spending 20 leaves 30. Spending 40 is more than 30, so spend throws before it touches money, and the catch prints the error. The failed attempt changed nothing, which is why spending 30 afterwards works and leaves 0.

    Traps

    • Checking after changing. If the subtraction came before the check, a failed request would still have changed the balance. Put the check first.
    • Printing instead of throwing. A method that prints an error message and returns normally tells the caller nothing. The caller's try would never reach its catch.
    • Catching the wrong type. A catch for a different exception class doesn't match, so the exception keeps travelling up.
    • An empty or silent catch. Swallowing an exception hides the problem. Here the catch reports it.

    Printing the exception object itself shows its class and message, for example java.lang.IllegalArgumentException: not enough money, while getMessage() gives only the message.

    Key takeaways

    • throw new SomeException("message") stops a method that can't do what was asked.
    • try and catch let the caller handle it and carry on.
    • Check first, change state afterwards, so a refused request leaves everything as it was.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free