Learn/Java/9. Handling errors
Lesson 9 of 15
Sign in

Java, lesson 9

Handling errors

Things go wrong: a user types ten where you expected 10, a file is missing, an amount is negative. Java reports these problems with exceptions. When something fails, the code throws an exception object, and normal execution stops. If nothing catches it, the program ends and prints a stack trace showing where it happened.

try and catch

Wrap code that might fail in a try block, and handle the failure in a catch block:

When parseInt throws, Java jumps straight to the matching catch, skipping the rest of the try block. Afterwards the program continues normally. gives a description of the problem.

2 exercises to try what you just read.

Exercise 1

Forgiving sum

Press Ctrl Enter or Check to test your code.

Exercise 2

Careful cash machine

Press Ctrl Enter or Check to test your code.

e.getMessage()

You can have several catch blocks, tried in order, or catch several types in one block with |:

Catch the most specific type you can handle. Catching Exception swallows every problem, including bugs you would rather see.

finally and try-with-resources

A finally block runs whether or not an exception happened, which makes it the place for cleanup. For anything that must be closed (files, readers, connections), Java has a better tool: try-with-resources. Resources declared in the parentheses are closed automatically at the end:

Throwing your own exceptions

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

IllegalArgumentException ("you passed me a bad value") and IllegalStateException ("I am not in a state to do that") cover most needs. For domain-specific errors, write your own class by extending Exception or RuntimeException:

Checked and unchecked exceptions

Java has two families:

  • Checked exceptions, such as IOException, extend Exception. They describe problems outside your control. The compiler forces you to either catch them or declare them with throws on the method, which is why main has been saying throws IOException.
  • Unchecked exceptions extend RuntimeException, such as NumberFormatException, NullPointerException and IllegalArgumentException. They usually signal a bug or bad input, and the compiler does not force you to handle them.

A good rule: validate early, throw with a clear message, and catch only where you can do something useful, such as skipping a bad line or showing a friendly error.

Further reading

  • What is an exception? (dev.java)
  • Catching and handling exceptions (dev.java)
  • Throwing exceptions (dev.java)

Read lines until the input ends. Each non-blank line should be a whole number, but some lines are garbage. Add up the valid numbers and count the invalid lines; ignore blank lines entirely. Use try/catch around Integer.parseInt.

Print Sum: <sum> and Skipped: <count>.

Sample input:

Sample output:

The first line is the starting balance (a whole number). Each following line is a command: deposit <amount> or withdraw <amount>.

Write a method static int withdraw(int balance, int amount) that returns the new balance, and throws an IllegalArgumentException with the message Invalid amount if amount <= 0, or Insufficient funds if amount is larger than the balance. Write a matching static int deposit(int balance, int amount) that throws Invalid amount for amount <= 0.

For each command, print OK <new balance> or Error: <message>. Finally print Balance: <balance>.

Sample input:

Sample output:

String text = "ten";
try {
    int n = Integer.parseInt(text);
    System.out.println("Got " + n);
} catch (NumberFormatException e) {
    System.out.println("Not a number: " + text);
}
System.out.println("The program keeps going");
try {
    int[] data = {1, 2, 3};
    int i = Integer.parseInt(input);
    System.out.println(data[i]);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index");
}
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
    System.out.println(in.readLine());
}   // in.close() is called for you, even if an exception occurs
static double divide(double a, double b) {
    if (b == 0) {
        throw new IllegalArgumentException("Cannot divide by zero");
    }
    return a / b;
}
class OutOfStockException extends RuntimeException {
    OutOfStockException(String item) {
        super(item + " is out of stock");
    }
}
10
abc
25

-5
4.5
Sum: 30
Skipped: 2
100
withdraw 30
withdraw 500
deposit -5
deposit 20
OK 70
Error: Insufficient funds
Error: Invalid amount
OK 90
Balance: 90