AI Hints
Home›Java Tutorial›What Exceptions Are, try and catch, and finally
Java · Lesson 91 of 120

What Exceptions Are

When things go wrong.

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

Sometimes things go wrong while a program runs. A number divided by zero, a file that's missing, an index that's too big. Java signals these problems with an exception.

  • Things go wrong
  • While running
  • Java throws an exception

An uncaught exception

This array has two boxes, but we ask for box two, the third one. Run it. Starting prints. Then an exception is thrown. Nobody handles it, so the program stops immediately. The last line never runs.

Main.javajava
public class Main {
    public static void main(String[] args) {
        System.out.println("Starting");
        int[] cups = {3, 5};
        System.out.println(cups[2]);
        System.out.println("This never prints");
    }
}
Output
Starting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of
bounds for length 2
    at Main.main(Main.java:5)

Reading a stack trace

Here, per person divides by the number of people. The second call passes zero. Run it. The first call prints three. The second throws an arithmetic exception. The message says divide by zero. And the lines starting with at show where it happened, line three, called from line eight.

Main.javajava
public class Main {
    static int perPerson(int total, int people) {
        return total / people;
    }

    public static void main(String[] args) {
        System.out.println(perPerson(12, 4));
        System.out.println(perPerson(12, 0));
    }
}
Output
3
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.perPerson(Main.java:3)
    at Main.main(Main.java:8)

Reading an exception

The first line gives the exception's type, and a message. Below it, each at line shows a method, and a line number. The top one is where the problem happened. Read from the top, and look for your own code.

keyvalue
TypeArithmeticException
Message/ by zero
at …method and line
Top linewhere it happened

Summary

An exception is Java's signal that something went wrong. If nobody handles it, the program stops, and prints a stack trace. Next, handling exceptions, with try and catch.

Key takeaways
  • Exceptions signal problems
  • Unhandled → program stops
  • Stack trace shows where
Next up: try and catch — handle the problem