Object-Oriented Programming with Java · Lecture Notes

Chapter 6: Exceptions

Even a correctly written program runs into surprises from the outside world. A file it needs to read may have been deleted, a user may type letters where a number is expected, a network connection may drop. Programs also contain faults of their own: division by zero, indexing past the end of an array, using a null reference. Java handles all of these through a single mechanism, the exception. This chapter first shows what an exception is and what happens to a program that does not catch one. It then traces the try, catch and finally blocks, automatic resource closing, and nested blocks step by step. The class hierarchy of exceptions, checked and unchecked exceptions, and the throw and throws keywords form the core of the chapter. The common exception classes are illustrated one by one. The chapter ends with writing custom exception classes, reading a stack trace, and good practices.

Learning outcomes

Concept
Define an exception, distinguish runtime problems as Exception and Error, and explain why exceptions are preferred to return codes.
Catching
Handle exceptions with try, catch, finally and try-with-resources, and trace the control flow step by step.
Hierarchy
Explain the relationships among Throwable, Error, Exception and RuntimeException, and why the order of catch blocks matters.
Types
Tell checked and unchecked exceptions apart, and apply the “catch or specify” rule.
Throwing
Throw an exception with throw, declare it with throws, and trace how an exception propagates up the call stack.
Practice
Recognize the common exception classes, write a custom exception class, and locate the source of a fault by reading the stack trace.

6.1The idea of an exception

Programming errors fall into three groups. A compile-time error is code that breaks the rules of the language: a semicolon is missing or a variable is undeclared. The compiler finds it and the program never runs. A logic error is silent: the program runs but produces a wrong result, for example when an average is computed by dividing the sum by the wrong number. The third group consists of problems that appear while the program is running. The code compiles, but at a particular moment, with a particular value, it cannot be executed. This chapter is about that third group.

6.1.1What is an exception?

Definition 6.1

An exception is an unexpected event that occurs while a program is running and disrupts its normal flow. In Java an exception is an object. It carries the type of the event, a descriptive message, and the place where the problem occurred.

Everyday examples come to mind at once. A file that is to be opened cannot be found. An integer is divided by zero. Code tries to reach the fifth element of a three-element array. A method is called through a null reference. None of these is something the compiler can foresee. Whether the file exists or whether the denominator is zero becomes known only while the program runs.

Two parties can create an exception. The first is the Java Virtual Machine (JVM). Situations such as division by zero or an array index out of range are noticed by the JVM itself, which creates the exception object on its own. The second is the programmer. When the programmer sees an invalid argument, for instance, the throw keyword deliberately creates an exception. In both cases the outcome is the same: there is an exception object and the normal flow has stopped.

The exception mechanism gives the programmer an orderly way to deal with unusual situations. Roughly speaking, when Java meets an exception it says: “I give up, I do not know what to do right now. Someone else handle this!” The code that resolves the problem does not have to be where the problem occurred.

Think of a restaurant. A waiter goes to the kitchen and learns that the requested dish has run out. The waiter cannot fix this alone and reports it to the manager. The manager either solves the problem by suggesting another dish to the customer, or passes it on to a higher level. An exception travels between methods in the same way. If the method that notices a problem cannot solve it, it reports it to the method that called it. This chain continues until the problem reaches a method that can solve it.

6.1.2Runtime errors: Exception and Error

When a problem arises while the program is running, the JVM throws it as a Throwable object. The name of this class means “something that can be thrown”. Throwable has two main branches, and they describe very different situations.

Table 6.1: The two main branches of runtime problems.
BranchWhat it describesWhat the program can doExample
Exception (Exception)An unusual situation that the program can anticipateCan catch it and recover10 / 0, arr[5] on a three-element array, a missing file
Error (Error)A serious problem at the JVM or system levelUsually not caught; the program terminatesStackOverflowError, OutOfMemoryError

The criterion behind the distinction in the table is the question “can the program recover from this situation?” If a file is not found, the program can ask the user for another file name. If the user types letters instead of a number, the program can warn and ask again. These are exceptions. If memory is exhausted or the call stack has overflowed, the program has no resources left with which to repair anything. These belong to the Error class.

The exception mechanism, together with the stack trace an exception leaves behind, is among the most powerful tools for finding and fixing the causes of runtime errors, that is, for debugging. The compiler reports compile-time errors, and a logic error leaves no trace. With a runtime error, however, the JVM prints the type of the problem, its message, and its exact location.

6.1.3An uncaught exception

Let us first see what happens when no precaution is taken. The following program divides an integer by zero.

public class Crash {
  public static void main(String[] args) {
    int num = 10, den = 0;
    System.out.println("Start");
    int result = num / den;
    System.out.println("Result: " + result);
    System.out.println("Done");
  }
}
Start
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Crash.main(Crash.java:5)

The program first prints Start. While line 5 evaluates num / den, the denominator is zero. Integer division by zero has no result. The JVM creates an ArithmeticException object and throws it. There is no code at this line to catch the exception. The caller of main is the JVM itself, so the exception reaches the JVM and the program terminates. The Result and Done lines are never printed.

line 3assignmentline 4Startline 510 / 0line 6skippedline 7skippedJVM: program terminates
Figure 6.1: Control flow with an uncaught exception. Lines 3 and 4 run; the exception occurs at line 5 and the JVM terminates the program. Lines 6 and 7 are skipped.

The message printed by the JVM carries three pieces of information. The Exception in thread "main" part says that the exception was not caught in the main thread. Next comes the fully qualified class name of the exception: java.lang.ArithmeticException. The / by zero after the colon is the message of the exception. The last line gives the location of the problem: the main method of the Crash class, line 5 of the file Crash.java. Lines beginning with at are called the stack trace.

Common mistake

Taking the “crash” of a program for a compile-time error. This program compiles without trouble. The compiler cannot know what value the variable den will have at run time. The problem appears only when the program is run. The phrase Exception in thread in the message shows that it is a runtime problem.

6.1.4Handle or declare

If an exception can occur in a method, the method has two options.

The first way is to handle the exception. The method places the code that may cause the exception in a try block and resolves the situation itself in a catch block. Consider a method that reads a settings file. If the file is not found (FileNotFoundException), the method shows the user a message and continues with default settings.

The second way is to make the exception the caller's problem. The method does not handle the exception; it declares in its signature, with the throws keyword, that it may throw this exception. The exception thereby becomes the problem of the code that calls the method. The calling code faces the same choice: it either handles the exception or passes it on to the method above it.

The question that decides which way to choose is: where is the place that can resolve the exception in a meaningful way? Code that takes the file name from the user can ask again in the “file missing” case. A low-level method that reads the file line by line does not talk to the user, and it does not know where the file name came from. For that method the right choice is to declare the exception; for user-interface code the right choice is to handle it.

6.1.5Exceptions instead of return codes

Exceptions are how a program reports that “something went wrong”. But “going wrong” is subjective. Is failing to find a name in an array an error, or an ordinary outcome? Before the exception mechanism became widespread, such situations were reported with a special return value. The following method returns -1 if it cannot find the name it is looking for.

public static int indexOf(String[] names, String name) {
  for (int i = 0; i < names.length; i++) {
    if (names[i].equals(name)) {
      return i;
    }
  }
  return -1;
}
// in main
String[] names = {"Ali", "Ayşe", "Can"};
System.out.println(indexOf(names, "Can"));
int k = indexOf(names, "Ece");   // k = -1
System.out.println(names[k]);
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    at ReturnCode.main(ReturnCode.java:14)

The first call finds "Can" at index 2 and 2 is printed. In the second call "Ece" is not in the array and the method returns -1. The calling code has forgotten to check this value. The access names[-1] throws an ArrayIndexOutOfBoundsException. The real problem arose in the search, but the error shows up somewhere else, at the array access. A fault whose source and symptom are in different places is harder to debug.

A return code has another problem: the error value can be confused with ordinary results. Here -1 works because it is an invalid index. For a method that measures temperature, however, -1 is a valid value, and the same method is left with no spare value to report an error.

The same method is written like this with an exception.

public static int find(String[] names, String name) {
  for (int i = 0; i < names.length; i++) {
    if (names[i].equals(name)) {
      return i;
    }
  }
  throw new IllegalArgumentException("Not found: " + name);
}
// in main
try {
  System.out.println(find(names, "Ece"));
} catch (IllegalArgumentException e) {
  System.out.println("Error: " + e.getMessage());
}
Error: Not found: Ece

If no match is found, the method throws an IllegalArgumentException. The message includes the name that was searched for: Not found: Ece. The caller can no longer forget to check. If the exception is not caught, the program stops at that point and clearly shows where the problem is. The error is not confused with a normal result: whenever the find method returns a number, that number is always a valid index.

For this reason special return codes such as -1 are generally avoided and Java's exception mechanism is preferred. The benefits of exceptions can be summed up in three points:

  • Error handling is explicit and consistent; the error value is not confused with a normal result.
  • The code is more readable and debugging is easier: the error is visible where it occurs.
  • Code is more reliable: exceptions, unlike unchecked return codes, do not slip by silently.
Common mistake

Turning every negative outcome into an exception. The result “not found” of a search method may be part of the program's ordinary flow. This is why String.indexOf in the Java library still returns -1. Exceptions are for situations that the caller does not expect and that cannot be described by an ordinary value. The decision is made according to the method's contract and is documented.

6.2try and catch

6.2.1The try and catch statements

The basic structure of error handling in Java is the try-catch statement. Code that may cause an error is written in the try block. What to do if an error occurs is written in the catch block.

Definition 6.2

The try block contains the statements that may cause an exception. The catch block runs and handles an exception of the specified type when one occurs in the try block; this is called catching the exception. The (ArithmeticException e) in the parentheses of catch is a parameter declaration: e is a reference to the thrown exception object.

try {
  // Code that may fail
  int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
  // Handle the error
  System.out.println("Error: " + e.getMessage());
}
Error: / by zero

The expression 10 / 0 throws an ArithmeticException. The type of the thrown object matches the type written in catch. The JVM binds this object to the parameter e and runs the catch block. e.getMessage() returns the message of the object, the text / by zero.

The flow of this structure is summarized by two rules:

  • If an exception occurs, the remaining lines of the try block are skipped and control passes to the matching catch block.
  • If no exception occurs, the catch block never runs.

In both cases the program continues its normal flow after the catch block. Because the exception was caught, the program does not crash.

trycatchnext codeexceptionno exception
Figure 6.2: The two paths of the try-catch flow. If there is no exception, control goes straight to the next code when try ends. If there is one, catch runs first, then control goes to the next code.

The code used here is an artificial example written to demonstrate an exception. With the literal expression 10 / 0 the compiler can see the problem too and issues a warning (division by zero). In real programs the denominator is usually a variable whose value becomes known only at run time.

6.2.2Code trace: the try-catch flow

This time the program from the uncaught-exception example is wrapped in a try-catch.

public class DivideDemo {
  public static void main(String[] args) {
    int num = 10, den = 0;
    System.out.println("Start");
    try {
      System.out.println("Before divide");
      int result = num / den;
      System.out.println("Result: " + result);
    } catch (ArithmeticException e) {
      System.out.println("Error: " + e.getMessage());
    }
    System.out.println("Done");
  }
}

The program advances line by line. Table 6.2 gives, for each step of the step-by-step trace in the slides, the line, the variables, and the output added at that step.

Table 6.2: Trace of the DivideDemo program.
StepLineCall stackVariablesNew output
13: int num = 10, den = 0;main()num=10, den=0—
24: System.out.println("Start");main()num=10, den=0Start
36: System.out.println("Before divide");main()num=10, den=0Before divide
47: int result = num / den;main()num=10, den=0—
59: } catch (ArithmeticException e) {main()num=10, den=0, e=ArithmeticException—
610: System.out.println("Error: " + e.getMessage());main()num=10, den=0, e=ArithmeticExceptionError: / by zero
712: System.out.println("Done");main()num=10, den=0Done

The first two steps have nothing to do with the exception. The variables are created and the first line outside the try prints Start. In step 3 the try block is entered; its first line runs without trouble and Before divide is printed. Step 4 is the heart of the matter. While num / den is evaluated, the JVM creates an ArithmeticException object and throws it. No assignment takes place; the variable result never receives a value.

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)✓println("Error: " + …)println("Done")
Figure 6.3: Step 5 of the trace. The first line of try ran successfully (green), the second threw an exception (red), the third was skipped (dashed). Because the types match, the catch block is running.

In step 5 the JVM looks for a suitable catch. The thrown object is an ArithmeticException, and that type is written in the catch. The types match and e refers to the exception object. The Result line has been skipped. In step 6, e.getMessage() is called and Error: / by zero is printed. In step 7 the catch block ends and the program returns to its normal flow: Done is printed.

Comparing the two programs is instructive. Without try-catch the program terminated at line 5 and Done was never printed. Now the same exception occurs, but the program runs to the end. The exception did not disappear; it was only handled.

Common mistake

Using a variable declared inside try outside the block. In the program above, int result is declared in the try block; its scope ends at the closing brace of the block. If System.out.println(result) is written after the try, the compiler reports cannot find symbol. If the variable is needed outside, it is declared before the try and given an initial value.

6.2.3Getting information from an exception object

The catch parameter is an ordinary reference. The exception object is also an ordinary object, and it inherits its methods from the Throwable class. The following code shows what these methods return.

try {
  int[] arr = new int[3];
  arr[5] = 7;
} catch (ArrayIndexOutOfBoundsException e) {
  System.out.println(e.getMessage());
  System.out.println(e);
  System.out.println(e.getClass().getSimpleName());
  e.printStackTrace();
}
Index 5 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
ArrayIndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    at ExceptionDemo.main(ExceptionDemo.java:5)
Table 6.3: Methods that give information about an exception object.
MethodWhat it returns
getMessage()The descriptive message only; null if no message was given
toString()The fully qualified class name, “: ” and the message; println(e) uses this
getClass()The actual class of the exception; its name without the package via getSimpleName()
printStackTrace()toString() and the stack trace; writes to System.err
getCause()The other exception that led to this one; null if none

The first line of the output comes from getMessage(): Index 5 out of bounds for length 3. The second line is written by println(e). println calls the object's toString() method, which joins the full class name with the message. The third line is just the short name of the class. The last two lines are produced by printStackTrace(). This method first writes the result of toString() and then the stack trace.

printStackTrace() writes not to standard output but to the error stream (System.err). Although the two streams appear on the same console, they are separate. For this reason the order of lines written to both streams may get mixed up on the console. Most integrated development environments (IDEs) show the error stream in red.

getCause() is for chained exceptions. A method can convert an exception it caught at a lower level into one of its own types and rethrow it. In doing so it attaches the old exception to the new object as its “cause”: new RuntimeException("Could not read settings", e). Code at the higher level can then reach the original source of the problem with getCause(). In this example the exception has no cause and the method returns null.

Common mistake

Assuming that getMessage() is always non-empty in a message shown to the user. For exceptions created without a message, such as new Exception(), getMessage() returns null. When logging, e.toString() or println(e) is safer: at least the class name is always printed.

6.2.4Multiple catch blocks and their order

More than one type of exception can occur in a block of code. Consider a program that divides two numbers taken from the user. The input may not be a number, the denominator may be zero, the input may be missing. A separate catch block is written for each kind of error, and each block contains the reaction specific to that type.

try {
  // Code that may fail
} catch (ArithmeticException e) {
  // Handle ArithmeticException
} catch (NullPointerException e) {
  // Handle NullPointerException
} catch (Exception e) {
  // All other exceptions
}

When an exception is thrown, the catch blocks are tried in order from top to bottom. The first matching block runs and the others are skipped. Here “matching” means that the thrown object is of the type in the catch or one of its subclasses. This is the logic of the instanceof operator. The final catch (Exception e) is the general case that catches all remaining exceptions.

NullPointerExceptionthrown objectArithmeticException✗ no match1st catchNullPointerException✓ runs2nd catchcatch Exceptionskipped3rd catch
Figure 6.4: Trying the catch blocks for a thrown NullPointerException. The first block does not match, the second runs, and the third is never tried.

Order matters when there is an inheritance relationship among the catch types. In the following code the general type is written before the specific type.

try {
  int result = 10 / 0;
} catch (Exception e) {
  System.out.println("General error");
} catch (ArithmeticException e) {
  System.out.println("Arithmetic error");
}
OrderError.java:7: error: exception ArithmeticException has already been caught
    } catch (ArithmeticException e) {

ArithmeticException is an Exception. The first block already catches every ArithmeticException that is thrown, so the second block can never run. The Java compiler does not allow an unreachable catch block and reports an error. The rule is simple: subclasses come before superclasses. The correct order is as follows.

} catch (ArithmeticException e) {
  System.out.println("Arithmetic error");
} catch (Exception e) {
  System.out.println("General error");
}

For types with no inheritance relationship the order does not matter. ArithmeticException and NullPointerException are not subclasses of each other. An object cannot be both at once, so at most one of the two blocks matches, whichever order they are written in.

Example 6.1

NumberFormatException is a subclass of IllegalArgumentException. What happens if catch (IllegalArgumentException e) is written first and catch (NumberFormatException e) second?

A compile-time error occurs: exception NumberFormatException has already been caught. Since every NumberFormatException is an IllegalArgumentException, the first block already catches it. If the two blocks are swapped, the code compiles. The specific case (“not a number”) is handled first, then the general case (“invalid argument”).

6.2.5Code trace: which catch runs?

The following method reads two numbers from an array of strings and divides one by the other. It has three separate catch blocks and a finally block. The finally block is the block that runs in every case, whether or not an exception occurs; here it prints one line at the end of each call.

static void divide(String[] input) {
  try {
    int x = Integer.parseInt(input[0]);
    int y = Integer.parseInt(input[1]);
    System.out.println("Result: " + (x / y));
  } catch (NumberFormatException e) {
    System.out.println("Not a number: " + e.getMessage());
  } catch (ArithmeticException e) {
    System.out.println("Zero: " + e.getMessage());
  } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Missing: " + e.getMessage());
  } finally {
    System.out.println("finally ran");
  }
}
// in main
divide(new String[] {"10", "abc"});
divide(new String[] {"10", "0"});
divide(new String[] {"10"});
Not a number: For input string: "abc"
finally ran
Zero: / by zero
finally ran
Missing: Index 1 out of bounds for length 1
finally ran
Table 6.4: Which catch ran in the three calls.
StepLineCall stackVariablesNew output
14: int y = Integer.parseInt(input[1]);main() → divide(input)input=["10", "abc"], x=10, y=——
26: } catch (NumberFormatException e) {
7: System.out.println("Not a number: " + e.getMessage());
main() → divide(input)input=["10", "abc"], x=10, y=—Not a number: For input string: "abc"
312: } finally {main() → divide(input)input=["10", "abc"], x=10, y=—finally ran
45: System.out.println("Result: " + (x / y));main() → divide(input)input=["10", "0"], x=10, y=0—
58: } catch (ArithmeticException e) {
9: System.out.println("Zero: " + e.getMessage());
main() → divide(input)input=["10", "0"], x=10, y=0Zero: / by zero
64: int y = Integer.parseInt(input[1]);main() → divide(input)input=["10"], x=10, y=—finally ran
710: } catch (ArrayIndexOutOfBoundsException e) {
11: System.out.println("Missing: " + e.getMessage());
12: } finally {
main() → divide(input)input=["10"], x=10, y=—Missing: Index 1 out of bounds for length 1 ⏎ finally ran

In the first call the input array is {"10", "abc"}. x becomes 10. Integer.parseInt("abc") then throws a NumberFormatException. The division line is skipped. The JVM tries the catch blocks in order. The first block is for NumberFormatException and it matches. The other blocks are not even looked at. Then finally runs.

In the second call both numbers are valid: x = 10, y = 0. The division throws an ArithmeticException. The first catch does not match and the second catch does. The message is again / by zero.

ArrayIndexOutOfBoundsException1st catch: NumberFormat✗2nd catch: Arithmetic✗3rd catch: ArrayIndexOutOfBounds✓finally
Figure 6.5: The ArrayIndexOutOfBoundsException thrown in the third call. The first two blocks do not match and the third does; then finally runs.

In the third call the array has a single element. The access input[1] throws an ArrayIndexOutOfBoundsException. The message says which index is invalid for an array of which length: Index 1 out of bounds for length 1. The first two catch blocks do not match and the third does; then finally runs.

In three calls three different exceptions occurred, and a separate block handled each one. What would happen if no exception occurred? In the call divide(new String[] {"10", "4"}) no catch runs. The method prints Result: 2 and finally ran. In integer division, 10 / 4 = 2.

6.2.6One catch, several types

Sometimes different exceptions get the same reaction. Writing a separate, identical catch for each leads to code duplication. Since Java 7, types can be combined in a single catch with the | sign. This construct is called multi-catch.

try {
  Object o = "Hello";
  Integer i = (Integer) o;
} catch (ClassCastException
    | NullPointerException e) {
  System.out.println("Type or null error: "
    + e.getClass().getSimpleName());
}
Type or null error: ClassCastException

"Hello" is a String object; it cannot be cast to Integer. The thrown ClassCastException fits one of the two types in the block, and the block runs. e.getClass().getSimpleName() shows which exception was actually caught.

Multi-catch has two rules. First, in this block e is implicitly final; a new value cannot be assigned to it. If e = null; is written, the compiler reports multi-catch parameter e may not be assigned. The same assignment is not forbidden in a single-type catch, but it is not good practice either.

The second rule is that the alternatives cannot be subclasses of one another.

} catch (FileNotFoundException
    | IOException e) {
Main.java:9: error: Alternatives in a multi-catch statement cannot be related by subclassing
    | IOException e) {
  Alternative FileNotFoundException is a subclass of alternative IOException

FileNotFoundException is a subclass of IOException. Writing IOException already covers the subtype, so writing both together is meaningless. The fix is to write only the supertype: catch (IOException e).

6.3finally and resource management

6.3.1The finally block

A program opens a file, reads data, and closes the file. What happens if an exception occurs during reading? The rest of the try block is skipped; if the closing line is also inside the try, it never runs. The file stays open. The operating system limits the number of files a program can have open at the same time. Files, network connections and database connections that are never closed pile up, and eventually the program cannot open any new resource. This problem is called a resource leak.

Definition 6.3

The finally block is the block written after the try and catch blocks that runs in every case. Whether or not an exception occurs, and whether or not it is caught, finally runs.

try {
  // Code that may fail
} catch (Exception e) {
  // All other exceptions
} finally {
  // Always runs
}

That finally runs “in every case” covers four situations:

  • There is no exception: try ends, then finally runs.
  • There is an exception and a catch catches it: the catch ends, then finally runs.
  • There is an exception but no catch matches: finally runs, and then the exception leaves the method.
  • There is a return inside try or catch: finally runs just before the method exits.

This guarantee ensures that certain steps are certain to run. The typical use is cleanup: closing files and network and database connections, releasing locks, deleting temporary files.

A try must be followed by at least one catch or a finally. Writing only try { } finally { } is valid. In that form the exception is not caught, but cleanup is still done. A lone try is a compile-time error: 'try' without 'catch', 'finally' or resource declarations.

The real exception to the rule is the call to System.exit(). This call stops the JVM immediately. If System.exit(0) runs inside try, finally does not run. A crash of the JVM itself or a shutdown of the computer also prevents finally, of course.

6.3.2Code trace: finally and return

The most surprising aspect of finally is its relationship with return. In the following method both try and catch return a value.

static int divide(int a, int b) {
  try {
    System.out.println("try started");
    int s = a / b;
    System.out.println("try ended");
    return s;
  } catch (ArithmeticException e) {
    System.out.println("catch: " + e.getMessage());
    return -1;
  } finally {
    System.out.println("finally");
  }
}
public static void main(String[] args) {
  System.out.println("Result = " + divide(10, 2));
  System.out.println("Result = " + divide(10, 0));
}
try started
try ended
finally
Result = 5
try started
catch: / by zero
finally
Result = -1
Table 6.5: Trace of the calls divide(10, 2) and divide(10, 0).
StepLineCall stackVariablesNew output
115: System.out.println("Result = " + divide(10, 2));main()——
23: System.out.println("try started");main() → divide(10, 2)a=10, b=2try started
34: int s = a / b;
5: System.out.println("try ended");
main() → divide(10, 2)a=10, b=2, s=5try ended
46: return s;main() → divide(10, 2)a=10, b=2, s=5—
511: System.out.println("finally");main() → divide(10, 2)a=10, b=2, s=5finally
615: System.out.println("Result = " + divide(10, 2));main()—Result = 5
716: System.out.println("Result = " + divide(10, 0));main()——
83: System.out.println("try started");main() → divide(10, 0)a=10, b=0try started
94: int s = a / b;main() → divide(10, 0)a=10, b=0—
108: System.out.println("catch: " + e.getMessage());main() → divide(10, 0)a=10, b=0, e=ArithmeticExceptioncatch: / by zero
119: return -1;main() → divide(10, 0)a=10, b=0, e=ArithmeticException—
1211: System.out.println("finally");main() → divide(10, 0)a=10, b=0finally
1316: System.out.println("Result = " + divide(10, 0));main()—Result = -1

In step 1 the argument of println must be evaluated. To do that, divide(10, 2) is called first. try starts, the division succeeds and s = 5. In step 4 return s runs. The return value 5 is prepared, but the method does not end at once. Before the method exits, the finally block must run. In step 5 finally prints. The catch is skipped, because there is no exception. Only in step 6 does the pending 5 return and Result = 5 is printed.

try { … }catch (ArithmeticException e)finally { … }pending return value: 5
Figure 6.6: Step 5. The try block ended with return s; the return value 5 is held pending. The method returns only after finally has run.

The second call is divide(10, 0). try started is printed. In step 9, 10 / 0 throws an exception. The rest of the try, that is, the try ended line and return s, is skipped. The catch matches and prints catch: / by zero. In step 11, return -1 runs: the value is ready, but again finally runs first. At the end -1 is returned. The conclusion is clear: in both cases finally ran just before the return.

Example 6.2

A method declares int s = 1;. Inside try it has s = 2; return s;, and inside finally it has s = 3; and System.out.print(s + " ");. What does System.out.println(g()) print?

3 2. When return s; runs, the return value is computed and stored: 2. Then finally runs, sets s to 3, and prints 3 . But the stored return value is a copy; the change to s does not affect it. The method returns 2. If there were also a return inside finally, that value would be returned. This usage silently erases the pending value and even a pending exception; for this reason it is discouraged.

Common mistake

Writing return inside finally. Even if try has thrown an exception, a return in finally destroys that exception and the method returns a value as if everything were fine. The error vanishes without a trace. finally is only for cleanup; it does not produce results.

6.3.3try-with-resources

Closing a resource with finally is correct, but the code gets long. The resource variable is declared as null before the try, finally checks whether it is null, and then calls close(). Since close() can also throw an exception, another try-catch is often needed. Java 7 introduced a construct that shortens this work.

Definition 6.4

try-with-resources is a try statement that opens a resource in the parentheses after the try keyword. A resource opened in the parentheses is closed automatically when the block ends: the JVM calls the resource's close() method. Closing happens even if the block ends with an exception. The resource class must implement the AutoCloseable interface.

The example in the slides uses a small resource class that prints its opening and closing.

class Resource implements AutoCloseable {
  private String name;
  Resource(String name) {
    this.name = name;
    System.out.println(name + " opened");
  }
  void use(int x) {
    System.out.println(name + " in use");
    int s = 10 / x;
  }
  @Override
  public void close() {
    System.out.println(name + " closed");
  }
}
try (Resource r = new Resource("file")) {
  r.use(0);
} catch (ArithmeticException e) {
  System.out.println("Error: " + e.getMessage());
}
file opened
file in use
file closed
Error: / by zero

The order of the output deserves attention. First the resource is opened and used. The division inside use(0) throws an exception. At this point, before moving to the catch, the resource is closed: file closed. Only after that does the catch run. In other words, the resource is closed before the catch.

Most classes in the Java library that act as resources implement AutoCloseable: file streams, Scanner, NIO channels, database connections. With these classes there is no need to write a finally and a null check. try-with-resources is the modern and safe way to close resources instead of writing finally.

A class that does not implement AutoCloseable cannot be used in the parentheses. Even if it has a method called shutdown(), the compiler reports incompatible types: try-with-resources not applicable to variable type. The name and signature of the method the JVM will call are fixed by the interface: close().

Common mistake

Forgetting the exception that close() declares. AutoCloseable.close() is declared with throws Exception. If a class writes close() keeping that declaration, try-with-resources itself can throw a checked exception. The compiler reports unreported exception Exception and points at the implicit close() call. The Resource class in the slides writes close() without throws, so this problem does not arise.

6.3.4Code trace: the opening and closing order of two resources

More than one resource can be opened in the parentheses; resources are separated by semicolons.

try (Resource a = new Resource("file");
     Resource b = new Resource("net")) {
  b.use(0);
  System.out.println("try end");
} catch (ArithmeticException e) {
  System.out.println("Error: " + e.getMessage());
} finally {
  System.out.println("finally");
}
file opened
net opened
net in use
net closed
file closed
Error: / by zero
finally
Table 6.6: Trace of a try-with-resources with two resources.
StepLineVariablesNew output
11: try (Resource a = new Resource("file");—file opened
22: Resource b = new Resource("net")) {—net opened
33: b.use(0);—net in use
43: b.use(0);——
52: Resource b = new Resource("net")) {—net closed
61: try (Resource a = new Resource("file");—file closed
75: } catch (ArithmeticException e) {
6: System.out.println("Error: " + e.getMessage());
—Error: / by zero
88: System.out.println("finally");—finally

Resources are opened in the order written: first file, then net. In step 3, b.use(0) first prints net in use, and then the 10 / 0 exception is thrown. The try end line is skipped. But control does not pass to the catch at once; first the resources are closed.

Resources (in opening order)fileclosednetclosedArithmeticException: / by zero
Figure 6.7: Step 6. Both resources were closed despite the exception. The exception object has not been caught yet; the catch comes next.

Closing is done in reverse order. The most recently opened b is closed first, then a. The reason is the possible dependency between resources. The second resource often uses the first; for example, a reader wraps a file stream. The outer wrapper is closed first, then the inner stream. After both resources are closed the catch runs, and finally the finally. The order is summarized as: open, use, close in reverse order, catch, finally.

What would the order be without an exception? In the call b.use(5) the division succeeds. try end is printed, then the resources are again closed in reverse order and finally runs:

file opened
net opened
net in use
try end
net closed
file closed
finally

6.3.5Nested try blocks

A try block can contain another try block. This structure is used to take a precaution specific to one part of a task while taking a general precaution for the whole task.

try {
  // Outer try block
  try {
    // Inner try block
    // Code that may fail
  } catch (Exception e) {
    // Inner catch block
  } finally {
    // Inner finally block
  }
} catch (Exception e) {
  // Outer catch block
} finally {
  // Outer finally block
}

If an exception occurs in the inner try, the JVM proceeds in this order:

  1. The catch blocks of the inner try are tried. If there is a suitable catch, it runs.
  2. If there is no suitable catch, the exception moves outward. The catch blocks of the outer try are tried and the first suitable one runs.
  3. If no catch matches, the exception leaves the method. If nobody finally catches it, the JVM's default handler terminates the program.

In every case, the finally block at each level the exception passes through runs.

6.3.6Code trace: the exception propagates outward

public static void main(String[] args) {
  try {
    System.out.println("Outer try");
    try {
      System.out.println("Inner try");
      String s = null;
      System.out.println(s.length());
    } catch (ArithmeticException e) {
      System.out.println("Inner catch");
    } finally {
      System.out.println("Inner finally");
    }
    System.out.println("Outer try cont.");
  } catch (NullPointerException e) {
    System.out.println("Outer catch: NPE");
  } finally {
    System.out.println("Outer finally");
  }
  System.out.println("Program goes on");
}
Outer try
Inner try
Inner finally
Outer catch: NPE
Outer finally
Program goes on
Table 6.7: Trace of the nested try program.
StepLineCall stackVariablesNew output
13: System.out.println("Outer try");main()—Outer try
25: System.out.println("Inner try");
6: String s = null;
main()s=nullInner try
37: System.out.println(s.length());main()s=null—
48: } catch (ArithmeticException e) {main()s=null—
511: System.out.println("Inner finally");main()s=nullInner finally
614: } catch (NullPointerException e) {
15: System.out.println("Outer catch: NPE");
main()e=NullPointerExceptionOuter catch: NPE
717: System.out.println("Outer finally");main()—Outer finally
819: System.out.println("Program goes on");main()—Program goes on

The outer try starts, then the inner try. The variable s receives the value null. In step 3, s.length() is called. A method cannot be called through a null reference; the JVM throws a NullPointerException. The inner catch catches only ArithmeticException and does not match. Before the exception leaves the inner level, the inner finally runs: Inner finally.

outer try {inner try { … s.length() }inner catch (ArithmeticException)✗inner finallyprintln("Outer try cont.")outer catch (NullPointerException)✓outer finallyprintln("Program goes on")
Figure 6.8: Step 6. The exception left the inner try; the inner catch did not match and the inner finally ran. The line Outer try cont. was skipped and the outer catch matched.

In step 6 the exception has moved to the outer level. In the outer try, the Outer try cont. line that follows the inner block is skipped. The outer catch is for NullPointerException and it matches. Then the outer finally runs. Because the exception has been handled, the program returns to its normal flow and Program goes on is printed.

Example 6.3

Let the inner try run Object o = "12"; Integer i = (Integer) o;. Let the inner catch catch NumberFormatException and the outer catch catch ClassCastException. Let there be a finally at each level and, at the end of the outer try, a line that prints outer try end. What does the program print?

inner finally, outer catch, outer finally (then the last line of the program prints end). o is a String object. Although "12" looks like a number, the cast does not convert the text to a number; it throws a ClassCastException. The inner catch does not catch this type. As the exception moves outward, the inner finally runs. outer try end is skipped, the outer catch catches, the outer finally runs, and the program continues.

6.4The exception hierarchy

6.4.1The Throwable tree

In Java the exception classes form a class hierarchy. At the root of the tree is the class Throwable. Throwable is the ancestor of everything that can be thrown. Only objects of Throwable and its subclasses can be thrown with throw and caught with catch. A line such as throw "error"; therefore does not compile: incompatible types: String cannot be converted to Throwable.

Throwable has two direct subclasses: Error and Exception. RuntimeException, one of the subclasses of Exception, forms a family of its own. Figure 6.9 shows this structure.

ThrowableErrorExceptionOutOfMemoryErrorStackOverflowErrorAssertionErrorserious system problemsother subclasses (checked)IOExceptionFileNotFoundExceptionSQLExceptionClassNotFoundExceptionParseExceptionInterruptedExceptionRuntimeExceptionArithmeticExceptionNullPointerExceptionClassCastExceptionIllegalArgumentExceptionNumberFormatExceptionIndexOutOfBoundsExceptionArrayIndexOutOfBoundsExceptionStringIndexOutOfBoundsException
Figure 6.9: The exception class tree. Blue boxes are checked exceptions. Orange boxes are RuntimeException and its subclasses; red boxes are Error and its subclasses. These two families make up the unchecked exceptions.

The hierarchy has a practical consequence: a catch block catches the type written in it and all of its subclasses. This is a natural consequence of inheritance. Every FileNotFoundException is also an IOException. So catch (IOException e) catches both FileNotFoundException and other input/output errors. Exceptions of the same family can be caught with a single supertype.

A few relationships in the tree are worth noting separately. NumberFormatException is a subclass of IllegalArgumentException. ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException are subclasses of IndexOutOfBoundsException. StackOverflowError and OutOfMemoryError derive not directly from Error but from its subclass VirtualMachineError. The figure omits this intermediate level for simplicity.

Java also supports writing new exception classes. An application-specific situation, for example “insufficient balance”, is added to this hierarchy with a class of its own. Such classes are attached to a branch of the tree and obey the same rules.

Example 6.4

new FileReader("missing.txt") throws a FileNotFoundException. Which of the types RuntimeException, Error, SQLException and IOException catches this exception?

Only IOException. The superclass chain of the exception is FileNotFoundException → IOException → Exception → Throwable. RuntimeException and SQLException are separate branches of Exception. Error is not in the Exception family at all. catch (Exception e) or catch (Throwable t) would also catch it, but they are not among the options.

6.4.2Error and Exception

The two big branches of the tree answer different questions.

Definition 6.5

Error indicates that the program has met a serious problem from which it cannot recover. Coping with these situations is mostly impossible and the program usually terminates. Exception represents situations that the program can anticipate and can often recover from; this is the type that is expected to be handled with try-catch.

Examples of Error are extreme situations: the program running out of memory (OutOfMemoryError), the call stack overflowing (StackOverflowError), a disk drive “disappearing”. These situations arise less from a line of the program than from the state of the environment. Catching Error in application code is not recommended. If memory is exhausted, the catch block itself may have no memory left to run.

Examples of Exception, on the other hand, are everyday problems: the file is missing, the network dropped, the input is invalid, the reference is null. Some of these come from outside the program; some are the programmer's mistake. RuntimeException, a subclass of Exception, mostly represents programmer errors. The distinction between checked and unchecked exceptions is based on this difference.

Error and Exception both derive from Throwable; so both can be thrown and, technically, both can be caught. But the one that “should be handled” is the Exception family.

Common mistake

Believing that “catch (Exception e) catches everything”. Exception does not include the Error family. A StackOverflowError caused by infinite recursion is not caught by this block and the program terminates with a stack trace. The type that catches everything is Throwable; but catching it is not recommended either, because it hides Errors.

6.5Checked and unchecked exceptions

6.5.1Two kinds of exceptions

Java exceptions fall into two groups according to the compiler's attitude.

Definition 6.6

A checked exception is an exception that the compiler verifies at compile time. The programmer must either handle or declare this exception. Classes that derive from Exception but not from RuntimeException are in this group. An unchecked exception, on the other hand, is not verified at compile time and arises at run time. RuntimeException, Error and their subclasses are in this group.

Checked exceptions describe situations known in advance to be possible. Every program that reads a file must face the possibility that the file is not found. The compiler asks for a plan for this possibility. Unchecked exceptions, on the other hand, are mostly the symptom of a programming error. If the compiler demanded a plan at every division, every array access and every method call, the code would become unreadable.

Exception typesUser-definedBuilt-inCheckedUncheckedClassNotFoundExceptionInterruptedExceptionIOExceptionInstantiationExceptionSQLExceptionFileNotFoundExceptionArithmeticExceptionClassCastExceptionNullPointerExceptionArrayIndexOutOfBoundsExceptionArrayStoreExceptionIllegalThreadStateException… extends Exception→ checked… extends RuntimeException→ unchecked
Figure 6.10: Exception types. Built-in exceptions are divided into checked and unchecked. A user-defined exception is checked if it extends Exception and unchecked if it extends RuntimeException.

6.5.2Checked exceptions: catch or declare

Java's rule for checked exceptions is the “catch or declare” rule. Code that may throw an exception is either handled inside a try-catch or declared in the method's signature with throws. This rule is verified at compile time; if it is not obeyed, the program does not compile.

The rationale is simple. However correctly a program that tries to read a file is written, the file may have been deleted in the meantime. This is not a programmer's mistake; it is a fact of the outside world. The compiler makes sure the programmer does not forget this possibility.

public void readFile() {
  FileReader reader = new FileReader("data.txt");
}
Main.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
  FileReader reader = new FileReader("data.txt");

The constructor of FileReader declares throws FileNotFoundException in its signature. The method readFile neither catches nor declares this exception. The compiler gives the two ways to fix the error in the message itself: must be caught or declared to be thrown. The fix by declaring is as follows:

public void readFile() throws FileNotFoundException {
  // Read the file
  FileReader reader = new FileReader("data.txt");
}

Now the method compiles. But the problem has not disappeared; it has passed to the code that calls the method. Every piece of code that calls readFile() must obey the same rule.

6.5.3Handling a checked exception

The second solution is to catch the exception inside the method.

public static void readFile2() {
  try {
    FileReader reader = new FileReader("data.txt");
    // Read the file
  } catch (FileNotFoundException e) {
    // Checked exception handled here
    System.err.println("File not found: " + e.getMessage());
    // Rethrow if needed:
    // throw e;
  }
}
File not found: data.txt (The system cannot find the file specified)

In this version the method catches the exception itself; it has no throws in its signature. The calling code needs to do nothing. The message is written to System.err, the error output stream. The second part of the message comes from the operating system. The output above was obtained on Windows: (The system cannot find the file specified). On Linux the same situation prints (No such file or directory).

The throw e; in the comment shows another possibility. The caught exception can be rethrown, for example after logging it. Then the exception again leaves the method, and the method signature must again declare throws FileNotFoundException.

Common mistake

Trying to catch a checked exception that is never thrown. If catch (FileNotFoundException e) is written for a try that contains no file operation, the compiler reports exception FileNotFoundException is never thrown in body of corresponding try statement. The compiler knows where checked exceptions can come from. catch (Exception e) does not produce this error, because Exception also covers the unchecked RuntimeExceptions.

6.5.4Unchecked exceptions

Unchecked exceptions need not be handled or declared. They are usually the result of logic errors or programmer mistakes: division by zero, use of null, exceeding an array bound. They do not have to be listed with throws or wrapped in try-catch; the compiler stays silent.

public void divide(int num, int den) {
  // Unchecked: ArithmeticException
  int result = num / den;
}

This method compiles and does not need throws. If den is zero, an ArithmeticException occurs at run time. The right fix for such an error is often not to catch it but to prevent it. The denominator is checked before dividing, and null is checked before use.

public void divide(int num, int den) {
  if (den == 0) {   // prevention
    System.out.println("Divisor cannot be 0");
    return;
  }
  int result = num / den;
}

In the prevention version the exception never occurs. The check catches the problem at its source and lets the programmer decide how to handle the situation. Here the method prints a message and returns early. In a real program it is often more correct to throw an IllegalArgumentException with a meaningful message, because that clearly tells the caller that it made a mistake.

6.5.5Comparing the three families

Table 6.8: Checked exceptions, unchecked exceptions and Error.
CheckedUncheckedError
SuperclassException (except RuntimeException)RuntimeExceptionError
Does the compiler check?Yes: handle or declareNoNo
Typical causeConditions outside the program (file, network, database)Programmer error (null, bounds, division)JVM or system problem
What to doCatch and recover, or pass on with throwsFix the code, check the inputUsually do not catch; terminate the program cleanly
ExamplesIOException, SQLException, ClassNotFoundExceptionNullPointerException, ArithmeticExceptionOutOfMemoryError, StackOverflowError
Example 6.5

Let us classify IOException, NumberFormatException, SQLException, NullPointerException, FileNotFoundException, ClassCastException and StackOverflowError as checked or unchecked.

For each class, look at the superclass chain. If RuntimeException or Error is in the chain, the class is unchecked. Checked: IOException, SQLException, FileNotFoundException. Unchecked: NumberFormatException (via IllegalArgumentException), NullPointerException, ClassCastException, and StackOverflowError, which is an Error.

Example 6.6

Written inside main with no try-catch and no throws, which of the lines Integer.parseInt("5"), Thread.sleep(100), new ArrayList<Integer>(-1) and Objects.requireNonNull(x) does not compile?

Thread.sleep(100). This method declares that it may throw the checked InterruptedException; the compiler reports unreported exception InterruptedException. The others throw at most an unchecked exception (NumberFormatException, IllegalArgumentException, NullPointerException). The compiler does not check these. The third line compiles but throws an exception when it runs.

6.6Throwing exceptions

6.6.1The throw statement

When the Java runtime meets an unexpected situation, it creates an exception object and throws it. The aim is to report the situation to the code at a higher level. The programmer can do the same with the throw keyword.

Definition 6.7

The throw statement throws an exception object: throw expression;. The value of the expression must be a Throwable object. The object is usually created on the same line with new, and a message is given to its constructor.

throw new Exception("This is an exception!");

An exception changes the normal flow of the program. The lines after throw do not run; control passes to a suitable catch. The thrown exception can be caught in the calling code with a try-catch. If it is handled nowhere, the JVM terminates the program and reports what went wrong and where.

try {
  throw new Exception("This is an exception!");
} catch (Exception e) {
  System.out.println(e);
}
java.lang.Exception: This is an exception!

There are many types that can be thrown: IOException, NullPointerException, IllegalArgumentException and custom classes written by the programmer. In the example above, println(e) prints the result of the object's toString(): the full name of the class and the message given to the constructor.

Common mistake

Writing code after throw in the same block. If throw runs unconditionally, the line after it can never be reached. The compiler notices this and reports unreachable statement. throw is usually inside an if; in that case the following lines run when the condition is false.

6.6.2The type that best describes the situation

When choosing an exception type, choose the class that best represents the situation. IllegalArgumentException suits an invalid argument, and IllegalStateException suits an operation that cannot be done in the object's current state. If none of the existing classes fits, a program-specific exception class is written.

class CustomException extends Exception {
  public CustomException(String message) {
    super(message);
  }
}
public static void check(int value)
    throws CustomException {
  if (value < 0) {
    // Check a condition and throw
    throw new CustomException("Value cannot be negative!");
  }
  // Value is OK: carry on
  System.out.println("Value OK: " + value);
}
// in main
try {
  check(5);
  check(-3);
  check(8);
} catch (CustomException e) {
  System.out.println("Caught: " + e.getMessage());
}
Value OK: 5
Caught: Value cannot be negative!

CustomException is a subclass of Exception. Because it does not derive from RuntimeException, it is a checked exception. So throws CustomException is mandatory in the signature of the check method. If this declaration is removed, the compiler reports unreported exception CustomException; must be caught or declared to be thrown.

The output has no Value OK: 8 line. The moment check(-3) throws an exception, the rest of the try is skipped; check(8) is never called.

6.6.3Code trace: throw

Let us trace the same program step by step together with the call stack. The call stack is the stack that holds the frames of the running methods; each method call pushes a frame onto the stack, and the frame is removed when the method ends.

static void check(int value) throws CustomException {
  if (value < 0) {
    throw new CustomException("Value cannot be negative!");
  }
  System.out.println("Value OK: " + value);
}
// in main
try {
  check(5);
  check(-3);
  check(8);
} catch (CustomException e) {
  System.out.println("Caught: " + e.getMessage());
}
Table 6.9: Trace of the throw program.
StepLineCall stackVariablesNew output
19: check(5);main()——
22: if (value < 0) {main() → check(5)value=5—
35: System.out.println("Value OK: " + value);main() → check(5)value=5Value OK: 5
410: check(-3);main()——
52: if (value < 0) {main() → check(-3)value=-3—
63: throw new CustomException("Value cannot be negative!");main() → check(-3)value=-3—
712: } catch (CustomException e) {main()e=CustomException—
813: System.out.println("Caught: " + e.getMessage());main()e=CustomExceptionCaught: Value cannot be negative!
914: }main()——

In step 1, main calls check(5) inside the try, and a new frame is pushed onto the stack. 5 < 0 is false; the throw line is skipped. Value OK: 5 is printed and the method returns normally. In step 4 the next call is check(-3). This time the condition is true.

Call stackmain()check(-3)CustomExceptionValue cannot be negative!
Figure 6.11: Step 6. A CustomException object was created and thrown in the frame of check(-3). Because the method has no catch, this frame will be discarded.

In step 6 the exception object is created with new and throw throws it. Line 5 of the method does not run. check has no catch; so its frame is discarded and the exception passes to main. In step 7 the rest of the try, that is check(8), is skipped and a suitable catch is found. In step 8, getMessage() returns the message given to the constructor: Caught: Value cannot be negative!. In the last step the catch ends and the program returns to its normal flow.

6.6.4The difference between throw and throws

The two keywords differ by a single letter, but their jobs are entirely different.

Table 6.10: Comparison of throw and throws.
throwthrows
PurposeThrows an exception (now)Declares the exceptions a method may throw (might happen later)
WhereIn the method body, as a statementIn the method signature, after the parameters
Followed byA single object: throw new X("…");One or more types: throws X, Y
Examplethrow new ArithmeticException("Division by zero");void divide(int x, int y) throws ArithmeticException

throw is an action; throws is a warning label. A method may never throw an exception that it declares with throws; the declaration only announces a possibility. Declaring unchecked exceptions with throws is not mandatory, but it can be written for documentation. The throws ArithmeticException in the table is a declaration of this kind.

Confusing the two words leads to two typical compile-time errors. In the first, throws is used in the body:

if (x < 0) {
  throws new IllegalArgumentException("negative");
}
Main.java:6: error: illegal start of expression
  throws new IllegalArgumentException("negative");

There is no statement called throws in a body; the compiler cannot recognize the line as the start of an expression. In the second, a checked exception is thrown without being declared:

static void f(int x) {
  if (x < 0) throw new Exception("negative");
}
Main.java:5: error: unreported exception Exception; must be caught or declared to be thrown
  if (x < 0) throw new Exception("negative");

Exception is a checked type because it is not a RuntimeException. There are two fixes: add throws Exception to the signature, or throw an unchecked type that describes the situation better, such as IllegalArgumentException. Because a negative argument is a programmer error, the second fix is more appropriate.

Common mistake

Believing that “throw can be used only in a catch block”. throw is a valid statement anywhere in a body: inside an if, in a loop, in a catch, even on the first line of a method. When used inside a catch it rethrows the caught exception.

6.6.5Calling methods that throw exceptions

When a method is called, the exceptions declared in its signature are taken into account and a suitable strategy is chosen. The file-reading method in the slides declares a checked exception.

public void readFile() throws FileNotFoundException {
  // Read the file
}

The first strategy is for the caller to handle the exception. The call is written inside a suitable try-catch block. This is the preferred way in most cases.

try {
  readFile();
} catch (FileNotFoundException e) {
  // Handle the missing file
  System.err.println("File not found: " + e.getMessage());
}

The second strategy is for the caller to declare the exception too. The calling method declares the same type with throws in its signature, and the problem passes to a higher level.

public void makeReport() throws FileNotFoundException {
  readFile();
}

The second way is less preferred than catching because it merely postpones the problem. Still, it is sometimes the right choice: if makeReport does not talk to the user, it cannot decide what to do when the file is not found either. The type in the declaration can be the thrown type itself or one of its superclasses. Writing throws IOException also compiles, because every FileNotFoundException is an IOException. If no strategy is chosen, the compiler reports unreported exception FileNotFoundException for the line readFile();.

Even the main method can write throws: public static void main(String[] args) throws IOException. Then the exception is passed all the way to the JVM, and the uncaught exception terminates the program. This is a practical shortcut in small experimental programs; in real applications it is more correct to give the user an understandable message.

6.6.6Code trace: exception propagation

Definition 6.8

Exception propagation is the movement of an uncaught exception down the call stack toward the calling method. Every method the exception passes through ends at that moment, and its frame is removed from the stack.

static int divide(int a, int b) {
  System.out.println("divide started");
  int s = a / b;
  System.out.println("divide ended");
  return s;
}
static int compute(int x) {
  System.out.println("compute started");
  int r = divide(x, 0);
  System.out.println("compute ended");
  return r;
}
public static void main(String[] args) {
  try {
    int result = compute(10);
    System.out.println("Result: " + result);
  } catch (ArithmeticException e) {
    System.out.println("main: " + e.getMessage());
  }
  System.out.println("Program ended");
}
compute started
divide started
main: / by zero
Program ended
Table 6.11: Propagation of the exception from divide to main.
StepLineCall stackVariablesNew output
115: int result = compute(10);main()——
28: System.out.println("compute started");main() → compute(10)x=10compute started
39: int r = divide(x, 0);main() → compute(10)x=10—
42: System.out.println("divide started");main() → compute(10) → divide(10, 0)a=10, b=0divide started
53: int s = a / b;main() → compute(10) → divide(10, 0)a=10, b=0—
69: int r = divide(x, 0);main() → compute(10)x=10—
715: int result = compute(10);main()——
817: } catch (ArithmeticException e) {
18: System.out.println("main: " + e.getMessage());
main()e=ArithmeticExceptionmain: / by zero
920: System.out.println("Program ended");main()—Program ended

In the first four steps the stack grows: main calls compute(10), and compute calls divide(10, 0). Now divide is at the top of the stack. In step 5, 10 / 0 is evaluated and the exception is born in divide. divide has no try; so the rest of the method does not run and its frame is discarded. divide ended is not printed.

Call stackmain()compute(10)ArithmeticException/ by zerodivide(10, 0)
Figure 6.12: Step 6. The frame of divide was discarded (struck through). The exception passed to the calling method, compute. Because there is no try here either, this frame will be discarded too.

In step 6 the exception passes to the caller, compute. There is no try here either. The compute ended line is skipped and the frame of compute is discarded as well. In step 7 the exception reaches main. The call is inside a try; the JVM looks for a suitable catch. The Result line is skipped. In step 8 the catch matches; the exception has been caught and the propagation has stopped. In the last step the program ends normally. If nobody had caught it, the exception would have reached the JVM and the program would have terminated.

The main idea of this trace is this: the place where the exception is born and the place where it is caught can be different methods. divide and compute do not solve the problem, and they do not get involved in it. The only method concerned with the problem is main. Each method does only its own job; the error-handling code is gathered in one place.

Example 6.7

c(x) prints c x; if x > 2 it throws IllegalArgumentException("x=" + x), otherwise it prints c ended. b(x) calls c(x) and then c(x + 2) inside a try and prints b ended; in its finally it prints b finally. main calls b(1) inside a try and prints main goes on; the catch prints main: followed by the message; at the very end end is printed. What is the output?

c 1, c ended, c 3, b finally, main: x=3, end. In the first call 1 > 2 is false and c ends normally. In c(3) the exception is born; c ended is not printed. b has no catch but it has a finally: before the exception continues on its way, b finally is printed. b ended and main goes on are skipped.

6.6.7How does the JVM handle an exception?

The process seen in the propagation trace works through the same steps for every exception:

  1. The JVM or a throw statement creates an exception object. The object contains the type, the message, and the stack trace of where it was created.
  2. In the method where the exception occurred, an enclosing try and a compatible catch are looked for.
  3. If none is found, the method ends at that moment; its finally block runs, if there is one. The exception passes to the calling method and the search continues there.
  4. If a suitable catch is found, it runs; the program continues from the line after the catch.
  5. If main does not catch it either, the JVM's default handler prints the stack trace and terminates the program, or more precisely that thread.
Definition 6.9

The process that moves down the call stack to find a suitable catch, discarding the frames on the way, is called stack unwinding.

main()try / catch ✓a()no catchb()no catchc()exception throwncall direction → ← path of the exception
Figure 6.13: Stack unwinding. The calls were made from left to right: main → a → b → c. The exception is born in c and moves in the opposite direction until it finds a catch.

A caught exception object is an ordinary object. After the catch block ends, if no other reference to it is held, the object is no longer used. The garbage collector cleans it from memory after a while.

6.7Runtime exceptions

6.7.1The RuntimeException family

RuntimeException and its subclasses represent exceptions caused by programmer errors or logic errors. They are not checked at compile time and handling them is not mandatory. But this does not mean ignoring them. The programmer deliberately prevents or handles these situations.

Table 6.12: Commonly encountered RuntimeException classes.
ClassWhen it occursExample
NullPointerExceptionWhen a member of a null reference is usedString s = null; s.length();
ArrayIndexOutOfBoundsExceptionIndex outside the array boundsint[] d = new int[3]; d[5] = 1;
ArithmeticExceptionInteger division by zero, overflow in exact arithmetic10 / 0
IllegalArgumentExceptionWhen an invalid argument is passed to a methodnew ArrayList<>(-1)
NumberFormatExceptionConverting a string that is not a valid numberInteger.parseInt("abc")
ClassCastExceptionWhen an object is not of the type it is being cast to(Integer) obj

The “line by line” examples in the slides give what happens when each line is tried on its own. In a real program the first exception interrupts the flow and the following lines do not run. All messages in this chapter were obtained with JDK 21, running each line inside a separate try.

6.7.2NullPointerException

A null reference points to no object. Calling a method through this reference, accessing a field, or reading the length of an array leads to a NullPointerException (NPE for short). This exception is among the most common sources of bugs.

String str = null;
int length = str.length();
Exception in thread "main" java.lang.NullPointerException:
  Cannot invoke "String.length()" because "str" is null

Before Java 14 this message was just java.lang.NullPointerException and did not say which reference was null. If several references were used on the same line (a.b().c()) it was hard to find the culprit. Since Java 14 the helpful message says which operation could not be performed and why. The variable name appears only if the class was compiled with debugging information (javac -g; IDEs do this by default). The same program compiled with plain javac cannot know the name and prints this:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null

There are several ways to prevent an NPE:

  • An explicit check with if (str != null).
  • Objects.requireNonNull(x, message): if x is null, it immediately throws an NPE with a meaningful message.
  • Objects.requireNonNullElse(x, fallback) (Java 9+): returns the fallback value if x is null.
  • The Optional class (Java 8+): represents the “there may be no value” case explicitly with a type.
  • Libraries: for example, the StringUtils class of Apache Commons Lang offers null-safe string operations.

The following code shows these ways together.

 1  String str = null;
 2  int length = str.length();
 3  Objects.requireNonNull(str, "str must not be null");
 4  Optional<String> optionalStr = Optional.ofNullable(str);
 5  length = optionalStr.map(String::length).orElse(0);
 6  String defaultValue = Objects.requireNonNullElse(str, "0");
 7  if (str != null) {
 8    System.out.println(str.length());
 9  }
10  System.out.println("Ali".equals(str));
Table 6.13: Results of the lines (each line tried on its own; str is null in every case).
LineResult
2NullPointerException: Cannot invoke "String.length()" because "str" is null
3NullPointerException: str must not be null
5length = 0: there is no value, so orElse(0) takes effect
6defaultValue = "0"
7–9The condition is false; nothing is printed, no exception
10false: the literal is in front, so a null argument is no problem

Line 3 throws the same exception as line 2; so what does requireNonNull gain? Two things. First, the programmer chooses the message. Second, and more important, the error is caught at its source. requireNonNull is used at the start of methods. A constructor whose parameter is null never creates the object. In this way a broken object does not wander around the program and throw an NPE much later in an unrelated place.

Line 5 uses Optional. Optional.ofNullable(str) produces an empty box if str is null, and otherwise a box containing str. map(String::length) takes the length of the content if the box is full and does nothing if it is empty. orElse(0) gives 0 if the box is empty. The result is not an NPE but 0.

Line 10 shows a common habit. "Ali".equals(str) is safe, because the method is called on the literal, and a literal is never null. str.equals("Ali"), on the other hand, throws an NPE when str is null.

Common mistake

Catching an NPE with catch (NullPointerException e) and moving on. An NPE is almost always a programming error: a variable was never assigned a value, or a method unexpectedly returned null. The right fix is to find where the null came from and correct it there. Catching only hides the symptom.

6.7.3Out-of-bounds exceptions

The valid indexes of an array run from 0 to length − 1. A negative index is also invalid. Accessing an index outside these bounds throws an ArrayIndexOutOfBoundsException.

This class is a member of the IndexOutOfBoundsException family. Which class is thrown on an out-of-bounds access depends on the structure being accessed:

  • an array (int[]), a Vector and the list returned by Arrays.asList(...) → ArrayIndexOutOfBoundsException;
  • ArrayList.get → IndexOutOfBoundsException (the superclass itself);
  • String.charAt → StringIndexOutOfBoundsException.

To catch them all at once, the common superclass is written: catch (IndexOutOfBoundsException e).

 1  int[] numbers = {1, 2, 3};
 2  int value = numbers[5];
 3  ArrayList<String> list = new ArrayList<>();
 4  String svalue = list.get(5);
 5  Vector<Integer> vector = new Vector<>();
 6  value = vector.get(10);
 7  String[] names = {"Alice", "Bob", "Charlie"};
 8  svalue = Arrays.asList(names).get(5);
 9  String str = "Hello";
10  char ch = str.charAt(10);
Table 6.14: Exceptions thrown on out-of-bounds access (each line tried on its own).
LineExceptionMessage
2ArrayIndexOutOfBoundsExceptionIndex 5 out of bounds for length 3
4IndexOutOfBoundsExceptionIndex 5 out of bounds for length 0
6ArrayIndexOutOfBoundsExceptionArray index out of range: 10
8ArrayIndexOutOfBoundsExceptionIndex 5 out of bounds for length 3
10StringIndexOutOfBoundsExceptionIndex 10 out of bounds for length 5

Line 4 is particularly instructive. Even if the list is created with a capacity such as new ArrayList<>(20), its size is 0, because no element has been added yet. The get method checks the index against the size, not the capacity. The message of the Vector in line 6 has a different form, because this old class builds its message itself. The list in line 8 is a view built on top of the names array; the access goes directly to the array and the array's exception is thrown.

The most common cause of an out-of-bounds access is a single character in the loop condition. The correct loop is bounded by length:

int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.length; i++) {
  System.out.print(numbers[i] + " ");
}
1 2 3

If the condition is written as i <= numbers.length, the loop runs one iteration too many. In the last iteration numbers[3] is accessed and an exception with the message Index 3 out of bounds for length 3 occurs. The safest way to walk over every element of an array is the for-each loop; there no index is written at all.

6.7.4ArithmeticException

ArithmeticException represents an error that occurs during a mathematical operation. The best-known example is dividing an integer by zero; both the / and % operators throw this exception. It has other sources too:

  • The “exact” methods of the Math class throw on overflow: addExact, multiplyExact, toIntExact …
  • BigDecimal provides high-precision arithmetic. It throws on division by zero and on a division whose result cannot be represented exactly (1/3).

Some operations, contrary to expectation, do not throw an exception:

  • double operations do not throw: 10.0 / 0 → Infinity, Math.sqrt(-1) → NaN.
  • Random.nextInt(0) throws an IllegalArgumentException, not an ArithmeticException: the bound must be positive.
  • When an ordinary int addition overflows, no exception occurs; the value wraps around. Integer.MAX_VALUE + 1 → -2147483648. This is called silent overflow. If the overflow needs to be noticed, Math.addExact is used.
 1  int result = 10 / 0;
 2  double dresult = Math.sqrt(-1);
 3  System.out.println(dresult);
 4  System.out.println(10.0 / 0);
 5  int t = Math.addExact(Integer.MAX_VALUE, 1);
 6  Random random = new Random();
 7  int randomNumber = random.nextInt(0);
 8  BigDecimal num1 = new BigDecimal("10");
 9  BigDecimal num2 = BigDecimal.ZERO;
10  BigDecimal bresult = num1.divide(num2);
Table 6.15: Arithmetic errors (each line tried on its own).
LineResult
1ArithmeticException: / by zero
3Prints NaN, no exception
4Prints Infinity, no exception
5ArithmeticException: integer overflow
7IllegalArgumentException: bound must be positive
10ArithmeticException: Division by zero

Division by zero in floating-point numbers produces special values according to the rules of the IEEE 754 standard. A positive number divided by zero gives Infinity, a negative number gives -Infinity, and 0.0 / 0 gives NaN (Not a Number). These values silently creep into calculations and spoil every later operation. For this reason double results are checked separately when necessary: Double.isNaN(x), Double.isInfinite(x).

The 1/3 example for BigDecimal was also run and tried. BigDecimal.ONE.divide(new BigDecimal("3")) gives this exception: Non-terminating decimal expansion; no exact representable decimal result. An infinite decimal expansion cannot be stored exactly. The fix is to give the division a scale and a rounding mode.

Example 6.8

Which of the expressions 10 / 0, 10 % 0, Math.toIntExact(3000000000L) and 10.0 / 0 does not throw an exception when it runs?

10.0 / 0. Floating-point division follows the IEEE 754 rules and produces Infinity. Integer division and the remainder operation with zero give ArithmeticException: / by zero. Because the value 3,000,000,000 does not fit in the int range (at most 2,147,483,647), toIntExact throws integer overflow.

6.7.5IllegalArgumentException

IllegalArgumentException indicates that a method received an invalid argument. It is an unchecked exception. The first job of a method is to check its arguments and, if necessary, throw this exception. In this way the error is stopped at its source.

public void setAge(int age) {
  if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative");
  }
  this.age = age;
}
public void setName(String name) {
  if (name.length() < 3) {
    throw new IllegalArgumentException("Min 3 characters");
  }
  this.name = name;
}

The Java library also uses this exception widely:

  • Arrays.copyOfRange(d, 5, 2): the start is greater than the end;
  • new ArrayList<>(-1): negative capacity;
  • the setPriority(11) method of Thread: the priority must be between 1 and 10;
  • new File(uri): the URI is not of the file: form.
 1  setAge(-5);
 2  setName("Al");
 3  int[] numbers = {1, 2, 3};
 4  Arrays.copyOfRange(numbers, 5, 2);
 5  List<Integer> list = new ArrayList<>(-1);
 6  File file = new File(URI.create("http://example.com/a.txt"));
 7  Thread thread = new Thread(task);
 8  thread.setPriority(11);
Table 6.16: Examples of invalid arguments (each line tried on its own).
LineException thrown
1IllegalArgumentException: Age cannot be negative
2IllegalArgumentException: Min 3 characters
4IllegalArgumentException: 5 > 2
5IllegalArgumentException: Illegal Capacity: -1
6IllegalArgumentException: URI scheme is not "file"
8IllegalArgumentException (no message)

Not every invalid situation gives this exception. new FileReader("invalid/file/path") throws the checked FileNotFoundException. new Thread(null) does not throw at all: a null task means “nothing to do”, and the thread ends immediately when started. The best-known subclass of IllegalArgumentException is NumberFormatException.

A good message states the invalid value and the expected range: "Age cannot be negative: " + age. The message-less exception in line 8 makes debugging harder. A programmer reading the message cannot tell what priority was given and what it should have been.

Common mistake

Forgetting null in argument checking. In the call setName(null), name.length(), the check itself, throws an NPE; the meaningful message the programmer wrote is never seen. The order of checks is null first, then the value: Objects.requireNonNull(name, "name must not be null"), followed by the length check.

6.7.6NumberFormatException and safe conversion

When a string is converted to a number and the string does not represent a valid number, a NumberFormatException occurs. Integer.parseInt, Double.parseDouble, Float.parseFloat, Short.parseShort, Long.parseLong, Byte.parseByte and their valueOf versions can throw this exception. The same exception occurs if the value is outside the range of the type: Byte.parseByte("300") gives the message Value out of range. Value:"300" Radix:10.

String strNumber = "abc";
int number = Integer.parseInt(strNumber);
strNumber = "123abc";
number = Integer.parseInt(strNumber);
String strDouble = "12.34abc";
double doubleValue = Double.parseDouble(strDouble);
String strShort = "45xyz";
short shortValue = Short.parseShort(strShort);
Table 6.17: Conversion calls and NumberFormatException messages.
CallMessage
Integer.parseInt("abc")For input string: "abc"
Integer.parseInt("123abc")For input string: "123abc"
Double.parseDouble("12.34abc")For input string: "12.34abc"
Short.parseShort("45xyz")For input string: "45xyz"

The "123abc" example shows the “all or nothing” rule of conversion. Although the 123 at the start of the string is valid, the string as a whole is not a number. parseInt does not return a partial result. NumberFormatException is a subclass of IllegalArgumentException. User input always carries this risk: either the input is checked beforehand or the exception is caught.

The conversion can be guarded in one place, in a helper method. For invalid input the method returns a default value.

static int safeParse(String text, int fallback) {
  try {
    return Integer.parseInt(text.trim());
  } catch (NumberFormatException e) {
    return fallback;
  }
}
// in main
System.out.println(safeParse(" 42 ", 0));
System.out.println(safeParse("forty", 0));
System.out.println(safeParse("10.5", -1));
42
0
-1

trim() removes leading and trailing whitespace. This is how the input " 42 " becomes 42. parseInt(" 42 ") alone would throw an exception, because a space is not a digit. "forty" is not a number; the default 0 is returned. "10.5" is not an int either; Double.parseDouble is used for decimal numbers.

The step-by-step trace in the slides runs the same method with three new inputs.

static int safeParse(String text, int fallback) {
  try {
    return Integer.parseInt(text.trim());
  } catch (NumberFormatException e) {
    return fallback;
  }
}
System.out.println(safeParse(" 7 ", 0));
System.out.println(safeParse("seven", 0));
System.out.println(safeParse("7.5", -1));
7
0
-1
Table 6.18: Trace of the safeParse method with three inputs.
StepLineVariablesNew output
18: System.out.println(safeParse(" 7 ", 0));——
23: return Integer.parseInt(text.trim());text=" 7 ", fallback=07
39: System.out.println(safeParse("seven", 0));——
43: return Integer.parseInt(text.trim());text="seven", fallback=0—
54: } catch (NumberFormatException e) {
5: return fallback;
text="seven", fallback=0, e=NumberFormatException0
610: System.out.println(safeParse("7.5", -1));——
73: return Integer.parseInt(text.trim());text="7.5", fallback=-1—
84: } catch (NumberFormatException e) {
5: return fallback;
text="7.5", fallback=-1, e=NumberFormatException-1

In the first call the text is " 7 ", with one space at the start and one at the end. trim() removes the spaces, "7" is converted to a number, and 7 is returned from inside the try. In the second call the text is "seven". parseInt throws an exception on a string that is not digits, and the return statement cannot complete.

textseventrim()sevencatch → return fallback = 0
Figure 6.14: The second call. The result of trim() is still seven; the conversion fails and the catch block returns the default value, 0.

The catch matches and the default value 0 is returned. The exception does not leave the method. In the third call the text is "7.5" and the default value is −1. The dot is not a digit; "7.5" is not a valid int. −1 is returned. The calling code goes on its way with the default value instead of an exception.

This approach has a cost. The default value must be chosen so that it cannot be confused with a valid result. safeParse("0", 0) returns 0, just like safeParse("seven", 0); safeParse("-1", -1) returns −1, just like safeParse("7.5", -1). If the default value cannot be told apart from valid inputs, it is more correct to pass the exception on to the caller. This is a small repeat of the return-code discussion.

6.7.7ClassCastException and instanceof

If an explicit cast is made when an object is not of the type it is being cast to, a ClassCastException occurs. What matters is not the type of the variable but the actual type of the object. After the line Object obj = "Hello"; the type of obj is Object, but the object it refers to is a String.

Raw-typed collections, that is, ArrayList, Map and Set written without a type parameter, accept objects of any kind. When an element of the wrong type is taken and cast, the cast fails. Sorted collections (TreeSet, TreeMap), on the other hand, also throw this exception when an element of a type that cannot be compared with the others is added.

 1  Object obj = "Hello";
 2  Integer number = (Integer) obj;
 3  ArrayList list = new ArrayList();
 4  list.add("Hello");
 5  number = (Integer) list.get(0);
 6  Map map = new HashMap();
 7  map.put("key", "Value");
 8  Integer value = (Integer) map.get("key");
 9  Set set = new HashSet();
10  set.add("Hello");
11  value = (Integer) set.iterator().next();
12  Object[] objArray = new String[5];
13  Integer[] intArray = (Integer[]) objArray;

Each of lines 2, 5, 8, 11 and 13 throws a ClassCastException. For example, the message of line 2 is:

class java.lang.String cannot be cast to class
java.lang.Integer

The full message in JDK 21 adds one more parenthesis: it says that both classes are in the java.base module and in the same loader. Line 13 is a cast between array types. objArray is actually a String[] and cannot be cast to Integer[]; in the message the arrays appear in the form [Ljava.lang.String;.

Before casting, the type of the object can be tested with instanceof:

Object obj = "Hello";
if (obj instanceof Integer) {
  Integer num = (Integer) obj;
  System.out.println("Number: " + num);
} else {
  System.out.println("obj is not an Integer");
}
obj is not an Integer

Since Java 16, pattern matching combines the test and the cast. If the condition is true, the variable num is already of type Integer; no separate cast line is needed.

if (obj instanceof Integer num) {
  System.out.println("Number: " + num);
}

A better solution is to move the problem to compile time. Generics tell the compiler what type of element a collection holds.

ArrayList<String> list = new ArrayList<>();
list.add("Hello");
Integer n = (Integer) list.get(0);
Main.java:8: error: incompatible types: String cannot be converted to Integer
Integer n = (Integer) list.get(0);

Instead of a runtime exception, a compile-time error is obtained. The error is found earlier, without the program ever being run. This is why generic types are preferred to raw types.

6.8Checked exception classes

6.8.1Commonly encountered classes

Checked exceptions represent situations that require the code to handle the error and recover appropriately. These situations mostly arise from conditions outside the program: the file system, the network, a database, another thread. The compiler makes handling these exceptions mandatory.

Table 6.19: Commonly encountered checked exceptions.
ClassPackageWhen
FileNotFoundExceptionjava.ioThe file to be opened does not exist or cannot be opened
IOExceptionjava.ioGeneral error in input/output operations (superclass)
SQLExceptionjava.sqlError in database access
ParseExceptionjava.textError while parsing text according to a format
ClassNotFoundExceptionjava.langA class to be loaded by name was not found
InterruptedExceptionjava.langA waiting thread was interrupted (Thread.sleep)
NotSerializableExceptionjava.ioAn attempt was made to write an object that cannot be serialized

All the classes in the table derive from Exception and have no RuntimeException in their chains. ClassNotFoundException has one more level in between (ReflectiveOperationException); NotSerializableException is linked to IOException through ObjectStreamException.

6.8.2FileNotFoundException and IOException

FileNotFoundException occurs when a file is to be opened and cannot be found. The same exception is thrown if the given path is a directory or if there is no permission to read the file.

try {
  FileReader fileReader = new FileReader("file.txt");
} catch (FileNotFoundException e) {
  // Handle the missing file
  System.out.println(e);
}
java.io.FileNotFoundException: file.txt
  (The system cannot find the file specified)

This class is a subclass of IOException; catch (IOException e) catches it too. A relative path ("file.txt") is looked up relative to the program's working directory. In development environments the working directory is usually the project folder, not the folder containing the source code. The file may be “in the wrong folder”. The typical reaction to this exception is to tell the user and ask for a new name, or to continue with default values.

The message the same exception gives for a directory was also tried: new FileReader(".") on Windows gives java.io.FileNotFoundException: . (Access is denied). Although the name of the class says “file not found”, the exception is used to mean “file could not be opened”.

IOException represents a general error in input/output operations and has many subclasses, such as FileNotFoundException. The following code reads a text file line by line.

try {
  BufferedReader reader =
    new BufferedReader(new FileReader(path));
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
  reader.close();
} catch (IOException e) {
  // Handle the I/O error
  e.printStackTrace();
}
first line
second line

The code works, but it has a flaw. If readLine() throws an exception, control passes directly to the catch and the line reader.close() never runs. The file stays open: this is a resource leak. The fix is try-with-resources:

try (BufferedReader reader =
    new BufferedReader(new FileReader(path))) {
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  System.out.println(e.getMessage());
}

In this version the reader is closed however the block ends. If the file does not exist, new FileReader(path) throws an exception; in that case no resource has been created to close, and the catch runs directly. catch (IOException e) catches both the opening error (FileNotFoundException) and read errors. Tried with the nonexistent missing.txt, the block prints the message missing.txt (The system cannot find the file specified).

6.8.3SQLException

SQLException is thrown when an error occurs during a database operation. The connection may fail, the SQL syntax may be wrong, the table may not exist, or the database driver may not be loaded. The exception object offers three methods that give details: getMessage(), getSQLState() and getErrorCode().

try {
  Connection connection =
    DriverManager.getConnection("jdbc:mysql://localhost/school");
  PreparedStatement preparedStatement =
    connection.prepareStatement("SELECT user_id FROM users");
  // Run the query and process the results
  ResultSet resultSet = preparedStatement.executeQuery();
  while (resultSet.next()) {
    // Process the results
    System.out.println("User ID: " + resultSet.getInt("user_id"));
  }
  // Close the connection
  connection.close();
} catch (SQLException e) {
  // Handle the SQLException
  System.out.println(e);
}
java.sql.SQLException: No suitable driver
found for jdbc:mysql://localhost/school

This program was run without the MySQL driver on the classpath. DriverManager cannot find a driver that recognizes a URL starting with jdbc:mysql:. In this case getSQLState() returns 08001 and getErrorCode() returns 0. State codes starting with 08 are the standard codes that describe connection errors.

The connection.close() call in the code has the flaw seen in the IOException example: if an exception occurs during the query, the connection stays open. A connection is also a resource and is closed with try-with-resources. Connection, PreparedStatement and ResultSet are all AutoCloseable and can be opened in the same parentheses.

6.8.4ParseException and ClassNotFoundException

ParseException (in the java.text package) is thrown when a string does not match the format being used to parse it.

try {
  SimpleDateFormat form =
    new SimpleDateFormat("dd/MM/yy");
  Date date = form.parse("01-01-2022");
} catch (ParseException e) {
  // Handle the parse error
  System.out.println(e);
}
java.text.ParseException: Unparseable date: "01-01-2022"

The format is dd/MM/yy; a / is expected between day and month. The text has a - instead. The parser reads the first two characters as the day and gets stuck at the third character. e.getErrorOffset() gives this position: 2, that is, the third character.

ClassNotFoundException is thrown when a class is to be loaded by its name (Class.forName) and cannot be found.

try {
  Class.forName("java.util.Scanner");
  System.out.println("Scanner loaded");
  // Try to load a missing class
  Class.forName("com.example.NonExistentClass");
} catch (ClassNotFoundException e) {
  System.out.println(e);
}
Scanner loaded
java.lang.ClassNotFoundException:
  com.example.NonExistentClass

java.util.Scanner is in the standard library and loads without trouble. com.example.NonExistentClass, on the other hand, is not on the classpath. Loading a class by name is used when working with classes not known at compile time, such as database drivers. Because the name is a string, the compiler cannot check it; whether the class will be found becomes known only at run time.

This exception should not be confused with NoClassDefFoundError from the Error family. With ClassNotFoundException the program itself asks for a class by name. With NoClassDefFoundError, a class that existed at compile time could not be found while the program was running; this is a deployment problem.

6.8.5NotSerializableException

Definition 6.10

Serialization is the conversion of an object into a stream of bytes. This stream can be written to a file or sent over a network. Later the stream is converted back into an object.

In Java, for the objects of a class to be serializable, the class must implement the Serializable interface. This interface has no methods; it is only a permission marker. If an object of a class that does not implement the interface is to be written, a NotSerializableException occurs.

class Point {               // not Serializable
  int x = 3, y = 4;
}
// in main
try (ObjectOutputStream outputStream =
    new ObjectOutputStream(new ByteArrayOutputStream())) {
  // Try to serialize the object
  Point notSerializableObj = new Point();
  outputStream.writeObject(notSerializableObj);
} catch (NotSerializableException e) {
  System.out.println(e);
} catch (IOException e) {
  System.out.println("Other I/O error: " + e);
}
java.io.NotSerializableException: Point

NotSerializableException is an indirect subclass of IOException. For this reason its catch is written before that of IOException. If the order were reversed, the compiler would report has already been caught. The fix is to add the interface to the class:

class Point implements Serializable {
  int x = 3, y = 4;
}

With this fix the object can be written and read back. The test program wrote the object to a byte array and read it again, getting back the values x = 3, y = 4.

6.9Error classes

Error classes represent system-level problems that fundamentally affect the normal running of the program. They are unchecked types. They generally arise not from a line of application code but from the state of the JVM and the runtime environment. The JVM itself throws them. Handling or declaring these errors is not recommended; letting the program terminate cleanly is a more suitable approach. Still, because they are Throwables, they can technically be caught.

Table 6.20: Commonly encountered Error classes.
ErrorWhen
OutOfMemoryErrorMemory (heap) is exhausted
StackOverflowErrorThe call stack overflowed; usually infinite recursion
AssertionErrorAn assert condition is false (only when -ea is on)
NoClassDefFoundErrorA class that existed at compile time was not found at run time
mainrecurserecurserecurserecurserecurserecurse…recursestack limiteach call adds a frame → StackOverflowErrorno base case: calls never return
Figure 6.15: Infinite recursion fills the call stack. Because there is no base case, no call returns; each call adds a new frame, and when the stack limit is reached a StackOverflowError is thrown.

The program in the slides demonstrates all three errors. Here the only purpose of catching Errors is to see them on the screen.

static void recurse() {
  recurse();         // no base case
}
public static void main(String[] args) {
  try {
    recurse();
  } catch (StackOverflowError e) {
    System.out.println("SOE -> " + e);
  }
  try {
    long[] arr = new long[Integer.MAX_VALUE];
  } catch (OutOfMemoryError e) {
    System.out.println("OOM -> " + e);
  }
  int age = -5;
  assert age >= 0 : "Negative age: " + age;
  System.out.println("assert passed");
}

The program is run in two ways. With java Demo the output is:

SOE -> java.lang.StackOverflowError
OOM -> java.lang.OutOfMemoryError: Requested array size exceeds VM limit
assert passed

With java -ea Demo the last line changes:

SOE -> java.lang.StackOverflowError
OOM -> java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Exception in thread "main" java.lang.AssertionError: Negative age: -5
    at Demo.main(Demo.java:17)

In the first try, the method recurse() calls itself endlessly. If the base case is forgotten in a recursion, each call adds a new frame and the stack fills up. In the second try, a long array of about two billion elements is requested. This array is larger than 16 GB; moreover, in the HotSpot JVM the maximum size of an array is slightly smaller than Integer.MAX_VALUE. The JVM rejects the request with the message Requested array size exceeds VM limit.

The third part is the assert statement. assert condition : message; throws an AssertionError with the message if the condition is false. But assertions (assert) are off by default; the JVM never runs them. That is why assert passed is printed on the first run. When they are turned on with the -ea (enable assertions) option, the condition is tested, an error is thrown because age is −5, and the program terminates. assert is for testing the programmer's assumptions during development; it is not used to check user input, because it can be switched off.

Example 6.9

The method static int f(int n) { return f(n + 1); } is called inside a try in main; catch (Exception e) prints caught; then end is printed. What happens when the program runs?

Neither caught nor end is printed. Each call adds a new frame to the stack; when the stack is full the JVM throws StackOverflowError. This is an Error, not in the Exception family. catch (Exception e) does not catch it; the program terminates with a long stack trace. In the listing the same at line is repeated hundreds of times. The compiler does not check for infinite recursion; the code compiles without trouble.

6.10Custom exceptions

6.10.1Writing a custom exception class

The exceptions in the Java library describe general situations. For the “insufficient balance” case in a banking program, or the “grade out of range” case in a grading system, the library has no special class. A developer can write custom exception classes to manage such situations that may arise in their own program.

Definition 6.11

A custom exception class is an exception class derived from Exception or RuntimeException that describes an application-specific situation.

public class MyException extends Exception {
  // Constructor
  public MyException(String message) {
    super(message);
  }
}

The constructor passes the message it receives up to the superclass with super(message). The message is stored inside Throwable; so getMessage() and toString() show the message automatically. If the super call is forgotten, getMessage() returns null.

Table 6.21: Choosing the superclass of a custom exception.
SuperclassResult
extends ExceptionChecked: the caller must handle it; recoverable business-rule violations
extends RuntimeExceptionUnchecked: incorrect use, programmer error
ThrowableExceptionRuntimeExceptionMyExceptioncheckedunchecked
Figure 6.16: Where custom exception classes fit in the hierarchy. Because MyException extends Exception, it is a checked exception.

An object of any class that extends Throwable can be thrown. In practice, however, Exception or RuntimeException is extended. Error is reserved for JVM problems. Extending Throwable directly leaves the class outside both families; code that writes catch (Exception e) cannot catch it.

A few rules are followed when writing a custom exception. The name of the class describes the situation and ends with Exception (or Error): InsufficientBalanceException, InvalidGradeException. An exception is an ordinary class; it can contain extra fields and methods. Information such as the missing amount, the faulty value or the name of the faulty field can be added as fields. If the compiler is run with -Xlint, it also reports that the serialVersionUID field is missing; Throwable is a serializable class. This is a warning, not an error.

6.10.2Throwing and catching a custom exception

public class MyExceptionTest {
  public static void main(String[] args) {
    try {
      doWork();
    } catch (MyException e) {
      System.out.println("Caught: " + e.getMessage());
    }
  }
  public static void doWork() throws MyException {
    if (true) {
      throw new MyException("Custom error occurred.");
    }
  }
}
Caught: Custom error occurred.

MyException is a checked exception because it derives from Exception. throws MyException is mandatory in the signature of doWork(). main uses the “handle” option by wrapping the call in a try.

The if (true) in the code is for demonstration only. Since throw is the last statement of the method here, writing it unconditionally would also compile. But if any code came after an unconditional throw, the compiler would report unreachable statement. In real programs the condition checks a business rule: is the balance sufficient, is the grade between 0 and 100, is the username empty?

Example 6.10

Let us write a checked InvalidGradeException class and a method int enterGrade(int grade). If the grade is outside 0–100, the exception is thrown with the message "Grade must be 0-100: …"; if it is valid, the grade is returned. Let the grades 85, 120 and 40 be entered in a loop.

class InvalidGradeException extends Exception {
  InvalidGradeException(String m) { super(m); }
}
static int enterGrade(int grade)
    throws InvalidGradeException {
  if (grade < 0 || grade > 100) {
    throw new InvalidGradeException(
        "Grade must be 0-100: " + grade);
  }
  return grade;
}
for (int g : new int[]{85, 120, 40}) {
  try {
    System.out.println("Saved: "
        + enterGrade(g));
  } catch (InvalidGradeException e) {
    System.out.println("Error: "
        + e.getMessage());
  }
}
Saved: 85
Error: Grade must be 0-100: 120
Saved: 40

Because the class extends Exception, throws is mandatory. The try is inside the loop: the error for 120 affects only that iteration and does not prevent 40 from being saved. If the try were outside the loop, the loop would also end at the first error and 40 would never be tried.

6.10.3An exception that carries information: a bank account

The real power of a custom exception is that it can carry information describing the situation. The following class stores the missing amount as well as the message.

class LowBalanceException extends Exception {
  private double deficit;

  public LowBalanceException(String msg, double deficit) {
    super(msg);            // kept in Throwable
    this.deficit = deficit;
  }

  public double getDeficit() {
    return deficit;
  }
}

The bank account that uses this class and the test code are as follows:

class Account {
  private double balance;
  Account(double balance) { this.balance = balance; }
  public void withdraw(double amount)
      throws LowBalanceException {
    if (amount > balance) {
      throw new LowBalanceException(
        "Insufficient funds", amount - balance);
    }
    balance -= amount;
    System.out.println("Balance: " + balance);
  }
}
// in main
Account acct = new Account(100);
try {
  acct.withdraw(30);
  acct.withdraw(90);
  acct.withdraw(10);
} catch (LowBalanceException e) {
  System.out.println(e.getMessage()
    + ", deficit: " + e.getDeficit());
}
Balance: 70.0
Insufficient funds, deficit: 20.0
Table 6.22: Trace of the bank account example.
StepLineCall stackVariablesNew output
115: Account acct = new Account(100);main()acct=→Account—
26: if (amount > balance) {main() → withdraw(30.0)amount=30.0, balance=100.0—
310: balance -= amount;
11: System.out.println("Balance: " + balance);
main() → withdraw(30.0)amount=30.0, balance=70.0Balance: 70.0
46: if (amount > balance) {main() → withdraw(90.0)amount=90.0, balance=70.0—
57: throw new LowBalanceException(
8: "Insufficient funds", amount - balance);
main() → withdraw(90.0)amount=90.0, balance=70.0—
620: } catch (LowBalanceException e) {main()e=→LowBalanceException—
721: System.out.println(e.getMessage()
22: + ", deficit: " + e.getDeficit());
main()e=→LowBalanceExceptionInsufficient funds, deficit: 20.0

In step 1 the Account object is created on the heap and acct refers to it; the balance is 100. In the call withdraw(30), 30 > 100 is false; there is no exception. The balance becomes 70 and Balance: 70.0 is printed. In step 4, withdraw(90) is called. This time 90 > 70 is true.

Stack: mainHeapacctAccountbalance = 70.0LowBalanceExceptionmessage: "Insufficient funds"deficit = 20.0e
Figure 6.17: Step 7. There are two objects on the heap: Account and LowBalanceException. The catch parameter e refers to the thrown exception object. The balance stayed at 70.

In step 5 an exception object is created on the heap. The object carries two pieces of information: the message "Insufficient funds" and deficit = 90 − 70 = 20.0. The object is thrown. Because the line balance -= amount did not run, the balance does not change. In step 6 the frame of withdraw is discarded and withdraw(10) is skipped. The catch matches; e refers to the very object that was thrown. In step 7 the information in the object is used: Insufficient funds, deficit: 20.0.

This example makes it plain that an exception is also an ordinary object. It is created with new, it has fields, and its methods are called. The code that catches it can react meaningfully with this information. For example, it could ask the user, “You are 20 TL short; do you still want to try?” A return code such as -1 could not have carried this much information.

A checked type was chosen for this class. Insufficient balance is a foreseeable situation and not a programmer's mistake. Every piece of code that wants to withdraw money must deal with this possibility; the compiler guarantees it.

Common mistake

Changing the state before checking the condition. If the line balance -= amount; were written before the if, the balance would already have dropped to −20 when the exception was thrown. The object would remain in a corrupted state. A good method does all the checks first, throws the exception if one is needed, and only then changes the state of the object.

6.11Stack trace and good practices

6.11.1What is a stack trace?

Definition 6.12

A stack trace is a report that shows which methods were on the call stack at the moment the exception occurred and where the exception occurred. The first line gives the type and message of the exception. Each following at line gives the class, method, file and line number of one call.

For an uncaught exception the JVM prints the stack trace to the error stream (System.err). It can also be printed at any time with e.printStackTrace(). The stack trace is the most important clue that helps the programmer understand and fix the error.

Exception in thread "main" java.lang.NullPointerException
    at com.example.MyClass.myMethod(MyClass.java:10)
    at com.example.MyClass.main(MyClass.java:6)

In this listing the main method called myMethod at line 6. The exception occurred at line 10 of myMethod. com.example is the name of the package and MyClass the name of the class. The list is read from top to bottom, from “most recently called” to “first called”.

Let us look at the method of reading on a more detailed example.

 1  public class TraceDemo {
 2    static int len(String text) {
 3      return text.length();
 4    }
 5    static void show(String name) {
 6      System.out.println(name + ": " + len(name));
 7    }
 8    public static void main(String[] args) {
 9      show("Ali");
10      show(null);
11      System.out.println("Done");
12    }
13  }
Ali: 3
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "text" is null
    at TraceDemo.len(TraceDemo.java:3)
    at TraceDemo.show(TraceDemo.java:6)
    at TraceDemo.main(TraceDemo.java:10)

A stack trace is read in four steps:

  1. The first line gives the type and message. Here the variable text is null and length() could not be called on it.
  2. The first at line is where the exception was born: the method len, line 3.
  3. Downward the call chain is read: main (10) → show (6) → len (3).
  4. Look first at the program's own lines. Lines of library classes (those starting with java.) are mostly not the source of the problem.

The real cause is often further down the list. The exception was born at line 3, but there is nothing wrong at line 3: the method len correctly computes the length of the text it is given. It was line 10 that sent the null value. The place to fix is often not where the exception was born but where the faulty value was produced.

The name "text" in the message appears when the class is compiled with debugging information (javac -g). The same program compiled with plain javac cannot know the name and prints this:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null

Line numbers, however, are printed in both cases, because javac puts line information into the class file by default.

6.11.2Code trace: where does the stack trace come from?

The lines of a stack trace are a snapshot: the moment the exception object is created, it records the call stack. The step-by-step trace in the slides shows how this snapshot is taken.

Table 6.23: Trace of the TraceDemo program.
StepLineCall stackVariablesNew output
19: show("Ali");main:9——
26: System.out.println(name + ": " + len(name));main:9 → show:6name=Ali—
33: return text.length();main:9 → show:6 → len:3text=Ali—
46: System.out.println(name + ": " + len(name));main:9 → show:6name=AliAli: 3
510: show(null);main:10——
66: System.out.println(name + ": " + len(name));main:10 → show:6name=null—
73: return text.length();main:10 → show:6 → len:3text=null—
83: return text.length();main:10 → show:6 → len:3text=null—
910: show(null);——Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "text" is null ⏎ at TraceDemo.len(TraceDemo.java:3) ⏎ at TraceDemo.show(TraceDemo.java:6) ⏎ at TraceDemo.main(TraceDemo.java:10)

In step 1, main calls show("Ali") at line 9. show calls len(name) at line 6. Each frame remembers at which line its method is. "Ali".length() returns 3 and the frame is removed. Ali: 3 is printed and show ends.

In step 5, main calls show(null) at line 10. null is passed as a parameter; at this point there is no problem yet. A reference being null is not an error; calling a method through null is. In step 7, null.length() is attempted and an NPE is thrown. At that moment there are three frames on the stack: len:3, show:6, main:10.

Stack trace = a snapshot of the stackat len(TraceDemo.java:3)at show(TraceDemo.java:6)at main(TraceDemo.java:10)
Figure 6.18: Step 8. The moment it is born, the exception object takes a snapshot of the stack. Each frame becomes an at line; the frame at the top of the stack is the first line of the list.

In step 8 the exception object records the stack. Each frame turns into an at line, and the topmost frame is written first. This is where the “reversed” order of the list comes from: the top of the stack is the head of the list. In the last step nobody has caught the exception. All three frames are discarded; the JVM prints the stack trace and terminates the program. Done is not printed.

Example 6.11

What does the following program print? According to the stack trace, at which line is the exception born, and where does the null value come from?

 1 public class School {
 2   public static void main(String[] args) {
 3     int[] a = {70, 80};
 4     int[] b = null;
 5     report("A", a);
 6     report("B", b);
 7     System.out.println("done");
 8   }
 9   static void report(String name, int[] d) {
10     System.out.println(name + ": " + average(d));
11   }
12   static double average(int[] grades) {
13     int t = 0;
14     for (int n : grades) {
15       t += n;
16     }
17     return (double) t / grades.length;
18   }
19 }
A: 75.0
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "<local2>" is null
    at School.average(School.java:14)
    at School.report(School.java:10)
    at School.main(School.java:6)

The first at line shows where the exception was born: average, line 14. The for-each loop at this line tries to read the length of a null array. The message says so too: Cannot read the array length. <local2> appears instead of a variable name because the program was compiled without -g. The chain from bottom to top is main (6) → report (10) → average (14). null was assigned to b at line 4 and sent at line 6. Because nobody catches it, line 7 does not run.

6.11.3Good practices in exception handling

Using the exception mechanism correctly is as important as knowing it. The following eight rules gather the lessons seen in the examples.

Catch a specific type
If possible, catch the expected type instead of catch (Exception e) and give a reaction suited to each kind. The general type also silently swallows unexpected errors.
Do not swallow exceptions
An empty catch { } hides the error. At the very least the exception is logged or reported to the user.
Close resources
Resources such as files and connections are closed with try-with-resources or finally.
Prevent what can be prevented
Do null, bounds and zero checks. Instead of catching a RuntimeException, fix the code.
Do not use them for flow control
Ordinary tasks such as leaving a loop are not done with exceptions. Exceptions are for exceptional situations; also, creating an exception object and recording the stack is much more expensive than an ordinary if.
A meaningful message
The message states the faulty value and the expectation: "Grade must be 0-100: 120".
Handle in the right place
The exception is caught where it can be resolved; if it cannot be resolved, it is passed on with throws.
Keep a log
Logging exceptions to a file makes it easier to trace the error afterwards. A message that vanishes from the user's screen stays in the log file.
Common mistake

Swallowing the exception: catch (Exception e) { }. This code compiles and runs, but the error disappears without a trace. The program keeps running in a wrong state and the problem shows up much later in an unrelated place. By then the stack trace of the real cause is long gone.

6.11.4final, finally and finalize

The three names are spelled alike, but their jobs are entirely different.

Table 6.24: final, finally and finalize().
What?Purpose
finalKeywordVariable: cannot be reassigned · method: cannot be overridden · class: cannot be subclassed
finallyKeyword (block)A cleanup block after try that runs in every case, whether or not there is an exception
finalize()A method of the Object classThe garbage collector used to be able to call it before deleting an object. When it will be called is undefined; it has been deprecated since Java 9.

The problem with finalize() is that it is unreliable. It is not clear when the garbage collector will delete an object, or even whether it will. It may never have run by the time the program ends. Since Java 18 this method has been marked for eventual removal; when a class that overrides it is compiled, -Xlint gives this warning: finalize() in Object has been deprecated and marked for removal. For resource cleanup, try-with-resources or finally is used, not finalize().

6.12Solved problems

The following problems are the example problems and exercises of the slides. Each solution is given step by step with its reasoning. All outputs were verified by running them with JDK 21.

Example 6.12 (Problem 1)

What does the following code print?

static int f() {
  try {
    System.out.print("A");
    int x = 5 / 0;
    System.out.print("B");
    return 1;
  } catch (ArithmeticException e) {
    System.out.print("C");
    return 2;
  } finally {
    System.out.print("D");
  }
}
// in main
System.out.println(" " + f());

Solution. To evaluate the argument of println, main first calls f(). try starts and A is printed. 5 / 0 throws an exception; B and return 1 are skipped. The catch matches, prints C and prepares 2 with return 2. Before the method exits, finally runs and prints D. Then 2 is returned. println prints " " + 2. Result: ACD 2. Because print adds no line break, the four pieces are on the same line.

Example 6.13 (Problems 2 and 3)
try {
  String s = "12a";
  int n = Integer.parseInt(s);
  System.out.println("Number: " + n);
} catch (IllegalArgumentException e) {
  System.out.println("IAE");
} catch (Exception e) {
  System.out.println("Exception");
}

What does the code print? What happens if the two catch blocks are swapped?

Solution. "12a" is not a valid integer; parseInt throws a NumberFormatException. The first catch is for IllegalArgumentException. Because NumberFormatException is a subclass of this class, the first block matches: the output is IAE. The second block is not tried.

If the blocks are swapped, catch (Exception e) comes first. This block also covers IllegalArgumentException, and the second block becomes unreachable. The code does not compile:

Main.java:12: error: exception IllegalArgumentException has already been caught
} catch (IllegalArgumentException e) {
Example 6.14 (Problem 4)
static void a() {
  System.out.print("a1 ");
  b();
  System.out.print("a2 ");
}
static void b() {
  System.out.print("b1 ");
  throw new IllegalStateException("!");
}
// in main
try {
  a();
  System.out.print("m ");
} catch (IllegalStateException e) {
  System.out.print("caught" + e.getMessage());
} finally {
  System.out.println(" end");
}

The exception is born in b(); there is no try in b() or a(). Which prints run? When does finally run?

Solution. main calls a(): a1 is printed. a calls b(): b1 is printed. b throws an IllegalStateException. b has no catch; its frame is discarded. The exception passes to a; a has no catch either and a2 is skipped. The exception reaches main; the rest of the try (m ) is skipped. The catch matches and prints caught!; because the message is "!", the two pieces are adjacent. Last of all, finally prints end and finishes the line. Result: a1 b1 caught! end.

Example 6.15 (Problem 5)
int[] d = {4, 0, 2};
int sum = 0;
for (int i = 0; i <= d.length; i++) {
  try {
    sum += 12 / d[i];
  } catch (ArithmeticException e) {
    sum += 100;
  } catch (ArrayIndexOutOfBoundsException e) {
    sum += 1000;
  }
}
System.out.println(sum);

What is sum?

Solution. The loop condition is i <= d.length; the loop runs for 0, 1, 2 and 3, that is, four iterations. Each iteration has its own try.

  • i = 0: 12 / 4 = 3; sum 3.
  • i = 1: 12 / 0 → ArithmeticException; +100, sum 103.
  • i = 2: 12 / 2 = 6; sum 109.
  • i = 3: d[3] → ArrayIndexOutOfBoundsException; +1000, sum 1109.

The output is 1109. Because the try is inside the loop, an exception in one iteration does not end the loop. In the iteration i = 1, in the expression sum += 12 / d[i] the division is evaluated before the assignment; when the exception occurs, nothing is added to the sum.

Example 6.16 (Problem 6)
try {
  throw new RuntimeException("X");
} finally {
  System.out.println("F");
}

What does the code print?

Solution. The try throws a RuntimeException. There is no catch, but there is a finally. Before the exception leaves the method, finally runs and prints F. Then the exception continues on its way; because it is not caught in main either, the program terminates:

F
Exception in thread "main" java.lang.RuntimeException: X
    at P6.main(P6.java:4)
Example 6.17 (Exercise: reading an age)

Let us write a method int readAge(String text) that converts a string to an age. If the text is not a number, a NumberFormatException occurs on its own; if the number is negative, the method throws an IllegalArgumentException. Try the inputs "20", "-3" and "twenty" with two catch blocks. What happens if the order of the catch blocks is reversed?

Solution. The method has three lines: int age = Integer.parseInt(text);, if (age < 0) throw new IllegalArgumentException("Negative age: " + age); and return age;. In the calling code, catch (NumberFormatException e) (“Not a number”) is written first, then catch (IllegalArgumentException e). The output: Age: 20, Negative age: -3, Not a number: twenty.

If the order is reversed, the NumberFormatException block can never be reached, because an NFE is an IllegalArgumentException. The compiler reports this error: exception NumberFormatException has already been caught.

Example 6.18 (Exercise: resources and the empty array)

How is code that closes a BufferedReader with finally written with try-with-resources? What should the method double average(int[] grades) do for an empty array?

Solution. The reader is opened in the parentheses: try (BufferedReader r = new BufferedReader(new FileReader(path))) { … } catch (IOException e) { … }. close() is called automatically; no finally, null check or nested try is needed.

The average of an empty array is undefined. Returning 0 is wrong, because 0 can be confused with a valid average; this is exactly the problem of the -1 return code. An empty array is an invalid argument: throw new IllegalArgumentException("Array is empty");. An unchecked type is chosen, because passing an empty array is the caller's mistake. In the test program, average(new int[0]) gave this exception, while the array {70, 80, 90} returned 80.0.

6.13Common mistakes

Mistakes with exceptions fall into two groups. Compile-time errors mostly arise from the checked-exception rule and from the order of catch blocks; their messages are clear. Logic errors, on the other hand, pass the compiler and silently spoil the behavior of the program. The following two tables gather the mistakes treated separately in the body of the chapter. The compiler messages were obtained with the javac tool of JDK 21.

Table 6.25: Common compile-time errors with exceptions.
Mistakejavac messageCause / fix
Forgetting a checked exception: new FileReader(name) with no try or throwsunreported exception FileNotFoundException; must be caught or declared to be thrownEither try-catch or throws.
Writing the general catch first: Exception first, then ArithmeticExceptionexception ArithmeticException has already been caughtSubclass first, superclass after.
Catching what is never thrown: catch (FileNotFoundException e) on a try with no file operationexception FileNotFoundException is never thrown in body of corresponding try statementRemove the catch.
Writing only try'try' without 'catch', 'finally' or resource declarationsAt least one catch or finally.
Code after throw in the same blockunreachable statementRemove the line, or make the throw conditional.
Using a variable from inside try outside itcannot find symbolDeclare the variable before the try.
Throwing a string: throw "error";incompatible types: String cannot be converted to ThrowableThrow an exception object.
throws in a bodyillegal start of expressionthrow in the body, throws in the signature.
Subclass and superclass in a multi-catchAlternatives in a multi-catch statement cannot be related by subclassingWrite only the supertype.
A resource that is not AutoCloseableincompatible types: try-with-resources not applicable to variable typeThe class implements AutoCloseable.
Table 6.26: Common logic errors with exceptions.
MistakeConsequenceFix
Swallowing the exception: catch (Exception e) { }The error disappears without a traceAt least log it or report it
Not checking a return code (-1)The error shows up elsewhere, as a different exceptionAn exception instead of a return code
return inside finallyThe pending exception and return value are silently erasedfinally only does cleanup
Closing the resource at the end of the tryThe resource stays open on an exception (leak)try-with-resources
Believing that catch (Exception e) catches everythingErrors such as StackOverflowError are not caughtErrors are not caught; the cause is fixed
Catching an NPE and moving onThe source of the null is hiddenFind where the null comes from
Throwing an exception with no messageThe message does not state the faulty valuePut the value and the expectation in the message
Using exceptions to control a loopHard-to-read and slow codeOrdinary cases are checked with if
Changing the state before the checkThe object is left corrupted after an exceptionCheck first, then change

6.14Summary

  • An exception is an event that disrupts the normal flow while a program is running. In Java an exception is an object; it carries its type, its message and where it occurred. The JVM or the programmer (throw) can create it.
  • Runtime problems have two branches: Exception if the program can recover, Error if there is a serious problem at the JVM or system level.
  • A method in which an exception can occur either handles it (try-catch) or declares it to the caller (throws). The right place is where the exception can be resolved in a meaningful way.
  • Special return codes (-1) mix the error with the normal result and slip by silently if unchecked. Exceptions solve these problems.
  • If an exception occurs in try, the rest of the block is skipped and the first matching catch runs. After the catch, the program continues its normal flow. If there is no exception, the catch does not run.
  • catch blocks are tried from top to bottom. A block catches the type written and all its subclasses. A subclass is written before its superclass; the reverse is the compile-time error has already been caught.
  • Since Java 7, catch (A | B e) collects the same reaction in a single block. The alternatives cannot be subclasses of one another; e is implicitly final.
  • finally runs in every case, even before a return inside try or catch. The return value is computed and stored first. System.exit() or a crash of the JVM prevents finally.
  • try-with-resources closes the AutoCloseable resources opened in the parentheses automatically. Resources are opened in the order written and closed in reverse order, before the catch.
  • In a nested try, an exception not caught at the inner level moves outward. The finally of every level it passes through runs.
  • The root of the hierarchy is Throwable; its two subclasses are Error and Exception. RuntimeException is a subclass of Exception.
  • For checked exceptions (those that derive from Exception but not from RuntimeException) the compiler enforces the “catch or declare” rule. The RuntimeException and Error families are not checked.
  • throw throws an object in the body; throws declares in the signature the types that may be thrown.
  • An uncaught exception propagates down the call stack toward the caller; the methods on the way end at that moment. This process is called stack unwinding. If main does not catch it either, the JVM prints the stack trace and terminates the program.
  • Commonly seen runtime exceptions: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException, NumberFormatException, ClassCastException. These are mostly not caught but prevented.
  • double operations do not throw exceptions (Infinity, NaN); an int addition that overflows silently wraps around. Math.addExact is used to check for overflow.
  • Commonly seen checked exceptions: IOException and its subclass FileNotFoundException, SQLException, ParseException, ClassNotFoundException, InterruptedException.
  • Errors (OutOfMemoryError, StackOverflowError, AssertionError) are not caught in application code. assert is turned on only with -ea.
  • A custom exception class is written by extending Exception (checked) or RuntimeException (unchecked); the message is passed with super(message). An exception can carry extra fields with information describing the situation.
  • The first line of a stack trace is the type and message; the first at line is where the exception was born. The call chain is read downward. The real cause is often on the line that produced the faulty value.
  • Good practices: catch a specific type, do not swallow the exception, close resources, and prevent what can be prevented. Exceptions are not used for flow control; the message is meaningful, the exception is handled in the right place and logged.

6.15Key terms

  • exception
  • runtime error
  • logic error
  • Error class
  • throw / catch
  • try-catch block
  • finally block
  • try-with-resources
  • checked exception
  • unchecked exception
  • exception propagation
  • call stack
  • stack trace
  • custom exception
  • debugging
  • assertion
  • serialization
  • garbage collector
  • overflow
  • cast (explicit conversion)
  • generics
  • method signature
  • stack unwinding
  • multi-catch
  • resource leak
  • pattern matching

6.16Test Yourself

  1. The outer try prints A. The inner try does throw new RuntimeException("x"); the inner catch catches only IllegalStateException and prints B; the inner finally prints C. After the inner block, the outer try prints D. The outer catch (RuntimeException e) prints outer: followed by the message. If all printing is done with print, what is the output?

    Answer

    AC outer:x. RuntimeException is the superclass of IllegalStateException, not a subclass; the inner catch does not match and B is not printed. Before the exception leaves, the inner finally prints C. D is skipped and the outer catch catches.

  2. What does the method static int f() { try { return 1; } finally { return 2; } } return? Why is this style not recommended?

    Answer

    2. The return 1 in the try prepares the value, but before the method exits finally runs and its own return replaces the pending value. The same style would also silently destroy an exception thrown in the try. This is why javac -Xlint gives the warning finally clause cannot complete normally.

  3. What are the results of the calls Integer.parseInt("12 ") and Double.parseDouble(" 12 ")?

    Answer

    The first throws NumberFormatException: For input string: "12 "; parseInt does not accept trailing whitespace and trim() is needed first. The second returns 12.0: Double.parseDouble strips leading and trailing whitespace itself. That two similar methods behave differently is one reason to always clean user input with trim().

  4. The parentheses of a try-with-resources contain K a = new K("A"); K b = new K(null). The constructor of K throws IllegalArgumentException("no name") if the name is null, and otherwise prints … opened; close() prints … closed. The block prints work; the catch prints catch followed by the message. What is the output?

    Answer

    A opened, A closed, catch no name. Because the constructor of the second resource throws an exception, b is never created and the block body does not run. The successfully opened a is still closed. Only resources that could be created are closed.

  5. Does catch (IOException | Exception e) compile? If the methods static void a() throws IOException and static void b() throws RuntimeException are called in main without a try, which call gives an error?

    Answer

    The multi-catch does not compile: IOException is a subclass of Exception, and the alternatives cannot be related by inheritance. The call a() gives the error unreported exception IOException. b() compiles: RuntimeException is unchecked; its declaration serves only as documentation.

  6. What do Integer.MAX_VALUE * 2 and Math.multiplyExact(Integer.MAX_VALUE, 2) give?

    Answer

    The first gives -2 with no exception: the result exceeds the int range and the value wraps around (silent overflow). The second throws ArithmeticException: integer overflow. The exact methods make overflow visible.

  7. For the class class X extends Exception { X(String m) { } }, what does new X("m").getMessage() return?

    Answer

    null. The constructor did not pass the message to the superclass with super(m). The compiler implicitly calls the no-argument super(), and the message field of Throwable stays empty. The correct form is X(String m) { super(m); }.

  8. A stack trace reads: java.lang.ArithmeticException: / by zero, followed by at Account.ratio(Account.java:12), at Account.report(Account.java:8), at Account.main(Account.java:3). Where was the exception born? Which method did main call, and at which line?

    Answer

    The exception was born at the first at line, at line 12 of the ratio method. Reading the list from bottom to top, main called report at line 3, and report called ratio at line 8. The zero denominator was most likely produced in report or in main; to fix it, one looks back from there.

6.17Further reading

  • Oracle, The Java Tutorials, “Lesson: Exceptions”: the official and free treatment of the topic, with the pages on try, catch, finally, try-with-resources and “Unchecked Exceptions — The Controversy”.
  • J. Bloch, Effective Java (3rd edition), Chapter 10, Items 69–77: discusses, with reasons, using exceptions only for exceptional conditions, choosing between checked and unchecked types, and not swallowing exceptions.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals (12th edition), Chapter 7 “Exceptions, Assertions, and Logging”: treats exceptions together with assert and logging, with a practical orientation.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 11 “Exceptions” and 14.20 “The try statement”: the precise definition of the checked-exception rule and of finally.

6.18References

  1. Oracle, The Java Tutorials: Lesson: Exceptions (Catching and Handling Exceptions; The try-with-resources Statement; Unchecked Exceptions — The Controversy).
  2. J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 11: Exceptions; 14.20 The try statement.
  3. Oracle, Java SE 21 API Documentation: java.lang.Throwable, Exception, RuntimeException, Error.
  4. P. Deitel and H. Deitel, Java: How to Program, 11th edition, Pearson (Chapter 11: Exception Handling: A Deeper Look).
  5. K. Sierra, B. Bates and T. Gee, Head First Java, 3rd edition, O'Reilly (Risky Behavior: exception handling).
  6. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th edition, Pearson (Chapter 7: Exceptions, Assertions, and Logging).
  7. J. Bloch, Effective Java, 3rd edition, Addison-Wesley (Chapter 10: Exceptions, Items 69–77).

Related pages: Chapter 6 slides · Study questions · Exception Flow simulator · Glossary · © Sercan Külcü. All rights reserved.