WeCodeAcademy

Java Exceptions

An exception is an error that happens while the program runs. Catch it with try / catch so the program can carry on. finally always runs.

ExampleJava
public class Main {
  static int divide(int a, int b) {
    if (b == 0) throw new IllegalArgumentException("Cannot divide by zero");
    return a / b;
  }

  public static void main(String[] args) {
    try {
      int[] nums = {1, 2, 3};
      System.out.println(nums[5]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Caught: " + e.getMessage());
    } finally {
      System.out.println("finally always runs");
    }

    try {
      System.out.println(divide(10, 0));
    } catch (IllegalArgumentException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
}
Output
Caught: Index 5 out of bounds for length 3
finally always runs
Error: Cannot divide by zero
Quick check

Which block always runs, error or not?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.