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.
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)
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)
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.
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.