Sub topic 1
What Happens When Things Go Wrong
Programs don't always run the way we plan. A user types letters where a number belongs. A file is missing. Code divides a number by zero. Java has a built-in way to report problems like these, called an exception. This chapter explains what an exception is, what it does to the normal order of your program, and how it travels from the place where the problem happened.
This chapter assumes you can write and run a simple Java program with a few methods.
Normal program flow
Program flow is the order in which your statements run. Usually Java runs statements top to bottom. When it reaches a method call, it jumps into that method. It runs the method's statements, then returns to the line right after the call.
Java tracks these jumps with the call stack. The call stack is a list of the methods that are currently running. The newest one sits on top. Calling a method adds an entry to the top, and returning from a method removes it.
Suppose main calls printReport, and printReport calls average. While average runs, the call stack looks like this:
| Position | Method | Waiting at |
|---|---|---|
| Top | `average` | running now |
| Middle | `printReport` | the line that called `average` |
| Bottom | `main` | the line that called `printReport` |
What an exception is
An exception is an object that describes a problem that happened while the program was running. When Java (or your code) hits a problem it cannot handle on the spot, it creates an exception object and throws it. Throwing means stopping the current work and sending the exception object up the call stack.
The exception object carries useful facts:
- Its type, such as
ArithmeticException. The type is the class of the object, and it names the kind of problem. - A message, such as
/ by zero, that gives details. - A record of where it happened, called the stack trace.
Here are some exceptions you will meet often:
| Exception type | Typical cause |
|---|---|
| `ArithmeticException` | Dividing an integer by zero |
| `NullPointerException` | Using a variable that holds `null` as if it pointed to an object |
| `ArrayIndexOutOfBoundsException` | Asking for `arr[5]` when the array has only 5 items (indexes 0 to 4) |
| `NumberFormatException` | Calling `Integer.parseInt("42x")` on text that is not a number |
How an exception changes the flow
When an exception is thrown, Java stops running the current method right away. The rest of the method does not run, and the method does not return a value. The program does not move on to the next line.
Java then looks for a handler. A handler is code that says "I know how to deal with this kind of problem." (You will write handlers with try and catch in a later chapter.) The search goes like this:
- Java checks the current method for a handler. If it finds one, the handler runs and the program carries on from there.
- If there is no handler, the method ends at once and is removed from the call stack. The exception moves to the method that called it.
- Java checks that caller for a handler, and so on down the stack.
- If the exception passes
mainand nobody has handled it, the program stops. Java prints the exception and its stack trace.
This movement down the call stack is called propagation. People also say the exception "bubbles up" to the callers. Either way, it travels from the method where the problem happened back toward main.
A worked example: an uncaught exception
Save this as Propagation.java. The comments show line numbers so you can match them to the output.
public class Propagation { // line 1
public static void main(String[] args) { // line 2
System.out.println("main: start"); // line 3
printReport(10, 0); // line 4
System.out.println("main: end"); // line 5
} // line 6
// line 7
static void printReport(int total, int count) { // line 8
System.out.println("printReport: start"); // line 9
int avg = average(total, count); // line 10
System.out.println("Average is " + avg); // line 11
} // line 12
// line 13
static int average(int total, int count) { // line 14
System.out.println("average: dividing"); // line 15
return total / count; // line 16
} // line 17
}Compile and run it:
javac Propagation.java
java PropagationThe output is:
main: start
printReport: start
average: dividing
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Propagation.average(Propagation.java:16)
at Propagation.printReport(Propagation.java:10)
at Propagation.main(Propagation.java:4)Here is what happened, step by step:
mainprinted its first line and calledprintReport.printReportprinted its first line and calledaverage.averagetried10 / 0on line 16. Integer division by zero is not allowed, so Java threw anArithmeticException.averagehad no handler, so it ended without returning a value.printReporthad no handler either. Line 11 never ran, soAverage is ...was never printed.mainhad no handler. Line 5 never ran, somain: endwas never printed.- Java printed the exception and stopped the program.
The lines under the message make up the stack trace. They list the call stack as it was when the exception was thrown, with the newest method first. You will learn to read stack traces in detail in a later chapter.
Stopping the propagation
Propagation stops at the first method that handles the exception. To preview this, change only main so it catches the problem. You will learn this syntax properly later.
public class Propagation {
public static void main(String[] args) {
System.out.println("main: start");
try {
printReport(10, 0);
} catch (ArithmeticException e) {
System.out.println("Could not compute: " + e.getMessage());
}
System.out.println("main: end");
}
static void printReport(int total, int count) {
System.out.println("printReport: start");
int avg = average(total, count);
System.out.println("Average is " + avg);
}
static int average(int total, int count) {
System.out.println("average: dividing");
return total / count;
}
}Output:
main: start
printReport: start
average: dividing
Could not compute: / by zero
main: endThe exception still ended average and printReport early. When it reached main, the handler caught it, and the program kept going, so main: end now prints.
Edge cases worth knowing
- Floating-point division is different.
10.0 / 0does not throw. It givesInfinity. Only integer division and remainder (/and%onintorlong) throwArithmeticException. - Partial work stays done. Anything that ran before the exception, such as the printed lines, has already happened. Throwing an exception does not undo it.
- Other threads. A thread is a separate path of execution inside your program. An uncaught exception ends only the thread it happened in. In a simple program, that thread is
main, which is why the message saysin thread "main".
Exercises
Exercise
In the first Propagation example, change the call on line 4 to printReport(10, 2). What does the program print, and why?
Show answer
It prints "main: start", "printReport: start", "average: dividing", "Average is 5", and "main: end". With count equal to 2, 10 / 2 is 5, so no exception is thrown and every method returns normally.
Exercise
An exception is thrown in method c. The call chain is main calls a, a calls b, and b calls c. Only a has a handler for that exception. Which methods end early, and where does the program continue?
Show answer
c and b end early, because neither has a handler, so the exception propagates through them. The handler in a runs, and after it finishes, a continues and eventually returns to main normally.
Exercise
Why does the stack trace in the first example list average first and main last?
Show answer
A stack trace lists the call stack as it was when the exception was thrown, with the newest method on top. average was the newest call, where the exception was thrown, and main was the oldest call at the bottom of the stack.