Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2022E

Section 10.4 Handling Exceptions Within a Program

This section will describe how to handle exceptions within the program rather than leaving them to be handled by the JVM.

Subsection 10.4.1 Trying, Throwing, and Catching an Exception

In Java, errors and other abnormal conditions are handled by throwing and catching exceptions. When an error or an exceptional condition is detected, you can throw an exception as a way of signaling the abnormal condition. This is like pulling the fire alarm. When an exception is thrown, an exception handler will catch the exception and deal with it (Figure 10.4.1). We will discuss try blocks, which typically are associated with catching exceptions, later in the section.
Figure 10.4.1. Exception Handler
If we go back to our avgFirstN() example, the typical way of handling this error in Java would be to throw an exception in the avgFirstN() method and catch it in the calling method. Of course, the calling method could be in the same object or it could belong to some other object. In the latter case, the detection of the error is separated from its handling. This division of labor opens up a wide range of possibilities. For example, a program could dedicate a single object to serve as the handler for all its exceptions. The object would be sort of like the program’s fire department.
To illustrate Java’s try/throw/catch mechanism, let’s revisit the CalcAvgTest program. The version shown in Listing 10.4.2 mimics the way Java’s default exception handler works. If the avgFirstN() method is called with an argument that is zero or negative, an IllegalArgumentException is thrown. The exception is caught by the catch clause in the CalcAvgTest.main() method.
try {
  CalcAverage ca = new CalcAverage();
  System.out.println( "AVG + " + ca.avgFirstN(0));
catch (IllegalArgumentException e) { // Exception Handler
Listing 10.4.2. In this version of the calcAvgTest program, an IllegalArgumentException thrown in CalcAverage.avgFirstN(), would be handled by the catch clause in CalcAvgTest.main().
Let’s go through this example step by step. The first thing to notice is that if the CalcAverage.avgFirstN() method has a zero or negative argument, it will throw an exception:
if (N <= 0)
   throw new IllegalArgumentException("ERROR: Illegal argument");
Note the syntax of the throw statement. It creates a new IllegalArgumentException object and passes it a message that describes the error. This message becomes part of the exception object. It can be retrieved using the getMessage() method, which is inherited from the Throwable class (Figure 10.3.1).
When a throw statement is executed, the JVM interrupts the normal execution of the program and searches for an exception handler. We will describe the details of this search shortly. In this case, the exception handler is the catch clause contained in the CalcAvgTest.main() method:
catch (IllegalArgumentException e) {  // Exception Handler
When an IllegalArgumentException is thrown, the statements within this catch clause are executed. The first statement uses the getMessage() method to print a copy of the error message. The second statement uses the printStackTrace() method, which is defined in Throwable and inherited by all Exception s, to print a trace of the method calls leading up to the exception. The last statement causes the program to terminate.
When we run this program, the following output will be generated as a result of the illegal argument error:
ERROR: Can't average 0 elements
java.lang.IllegalArgumentException: ERROR: Illegal argument
   at java.lang.Throwable.fillInStackTrace(Native Method)
   at java.lang.Throwable.<init>(
   at java.lang.Exception.<init>(
   at java.lang.RuntimeException.<init>
   at java.lang.IllegalArgumentException.<init>
   at CalcAverage.avgFirstN(Compiled Code)
   at CalcAvgTest.main(
Thus, as in the previous example of Java’s default exception handler, our exception handler also prints out a description of the error and a trace of the method calls that led up to the error. However, in this example, we are directly handling the exception rather than leaving it up to Java’s default exception handler. Of course, this example is intended mainly for illustrative purposes. It would make little sense to write our own exception handler if it does nothing more than mimic Java’s default handler.
Finally, note that the catch clause is associated with a try block. The handling of exceptions in Java takes place in two parts: First, we try to execute some statements, which may or may not lead to an exception. These are the statements contained within the try clause:
try {
    CalcAverage ca = new CalcAverage();
    System.out.println( "AVG + " + ca.avgFirstN(0));        
Second, we provide one or more catch clauses to handle particular types of exceptions. In this case, we are only handling IllegalArgumentException s.
As we said earlier, throwing an exception is like pulling a fire alarm. The throw occurs somewhere within the scope of the try block. The “fire department” in this case is the code contained in the catch clause that immediately follows the try block. This is the exception handler for this particular exception. There’s something like a game of catch going on here: Some method within the try block throws an Exception object, which is caught and handled by the catch block located in some other object (Figure 10.4.4).
Figure 10.4.4. Playing catch: In this design, the IllegalArgumentException is thrown by the CalcAverage.avgFirstN() method and caught by the catch clause within CalcAvgTest.main() method.

Subsection 10.4.2 Separating Error Checking from Error Handling

As we see in the CalcAvgTest example, an important difference between Java’s exception handling and more traditional approaches is that error handling can be separated from the normal flow of execution within a program. The CalcAverage.avgFirstN() method still checks for the error and it still throwsIllegalArgumentException if N does not satisfy the method’s precondition. But it does not contain code for handling the exception. The exception-handling code is located in the CalcAvgTest class.
Thus, the CalcAvgTest program creates a clear separation between the normal algorithm and the exception-handling code. One advantage of this design is that the normal algorithm is uncluttered by error-handling code and, therefore, easier to read.
Another advantage is that the program’s response to errors has been organized into one central location. By locating the exception handler in CalcAvgTest.main(), one exception handler can be used to handle other errors of that type. For example, this catch clause could handle allIllegalArgumentException s that get thrown in the program. Its use of printStackTrace() will identify exactly where the exception occurred. In fact, because a Java application starts in the main() method, encapsulating all of a program’s executable statements within a single try block in the main() method will effectively handle all the exceptions that occur within a program.

Subsection 10.4.3 Syntax and Semantics of Try/Throw/Catch

A try block begins with the keyword try followed by a block of code enclosed within curly braces. A catch clause or catch block consists of the keyword catch, followed by a parameter declaration that identifies the type of Exception being caught, followed by a collection of statements enclosed within curly braces. These are the statements that handle the exception by taking appropriate action.
Once an exception is thrown, control is transferred out of the try block to an appropriate catch block. Control does not return to the try block.
The complete syntax of the try/catch statement is summarized in Listing 10.4.7.
try {
      // Block of statements
      // At least one of which may throw an exception
      if ( /* Some condition obtains */ )
          throw new ExceptionName();
 } catch (ExceptionName ParameterName) {
     // Block of statements to be executed
     // If the ExceptionName exception is thrown in try
 }  catch (ExceptionName2 ParameterName) {
     // Block of statements to be executed
     // If the ExceptionName2 exception is thrown in try
...  // Possibly other catch clauses
 } finally {
     // Optional block of statements that is executed
     // Whether an exception is thrown or not
Listing 10.4.7. Java’s try/catch statement.
The try block is meant to include a statement or statements that might throw an exception. The catch blocks—there can be one or more—are meant to handle exceptions that are thrown in the try block. A catch block will handle any exception that matches its parameter class, including subclasses of that class. The finally block clause is an optional clause that is always executed, whether an exception is thrown or not.
The statements in the try block are part of the program’s normal flow of execution. By encapsulating a group of statements within a try block, you thereby indicate that one or more exceptions may be thrown by those statements, and that you intend to catch them. In effect, you are trying a block of code with the possibility that something might go wrong.
If an exception is thrown within a try block, Java exits the block and transfers control to the first catch block that matches the particular kind of exception that was thrown. Exceptions are thrown by using the throw statement, which takes the following general form:
throw new ExceptionClassName(OptionalMessageString);
The keyword throw is followed by the instantiation of an object of the ExceptionClassName class. This is done the same way we instantiate any object in Java: by using the new operator and invoking one of the exception’s constructor methods. Some of the constructors take an OptionalMessageString, which is the message that gets returned by the exception’s getMessage() method.
A catch block has the following general form:
catch (ExceptionClassName ParameterName) {
    // Exception handling statements
A catch block is very much like a method definition. It contains a parameter, which specifies the class of exception that is handled by that block. The ParameterName can be any valid identifier, but it is customary to use e as the catch block parameter. The parameter’s scope is limited to the catch block, and it is used to refer to the caught exception.
The ExceptionClassName must be one of the classes in Java’s exception hierarchy (see Figure 10.3.1). A thrown exception will match any parameter of its own class or any of its superclasses. Thus, if an ArithmeticException is thrown, it will match both an ArithmeticException parameter and an Exception parameter, because ArithmeticException is a subclass of Exception.
Note that there can be multiple catch clauses associated with a given try block, and the order with which they are arranged is important. A thrown exception will be caught by the first catch clause it matches. Therefore, catch clauses should be arranged in order from most specific to most general (See the exception hierarchy in Figure 10.3.1). If a more general catch clause precedes a more specific one, it will prevent the more specific one from executing. In effect, the more specific clause will be hidden by the more general one. You might as well just not have the more specific clause at all.
To illustrate how to arrange catch clauses, suppose an ArithmeticException is thrown in the following try/catch statement:
try {
     // Suppose an ArithmeticException is thrown here} catch (ArithmeticException e) {
     System.out.println("ERROR: " + e.getMessage() );
     System.exit(1);} catch (Exception e) {
     System.out.println("ERROR: " + e.getMessage() );
In this case, the exception would be handled by the more specific ArithmeticException block. On the other hand, if some other kind of exception is raised, it will be caught by the second catch clause. The Exception class will match any exception that is thrown. Therefore, it should always occur last in a sequence of catch clauses.

Subsection 10.4.4 Restrictions on the try/catch/finally Statement

There are several important restrictions that apply to Java’s exception-handling mechanism. We’ll describe these in more detail later in this chapter.
  • A try block must be immediately followed by one or more catch clauses and a catch clause may only follow a try block.
  • A throw statement is used to throw both checked exceptions and unchecked exceptions, where unchecked exceptions are those belonging to RuntimeException or its subclasses. Unchecked exceptions need not be caught by the program.
  • A throw statement must be contained within the dynamic scope of a try block, and the type of Exception thrown must match at least one of the try block’s catch clauses. Or the throw statement must be contained within a method or constructor that has a throws clause for the type of thrown Exception.

Subsection 10.4.5 Dynamic Versus Static Scoping

How does Java know that it should execute the catch clause in CalcAvgTest.main() when an exception is thrown in avgFirstN()? Also, doesn’t the latest version of avgFirstN()(Listing 10.4.2) violate the restriction that a throw statement must occur within a try block?
An exception can only be thrown within a dynamically enclosing try block. This means that the throw statement must fall within the dynamic scope of an enclosing try block. Let’s see what this means.
Dynamic scoping refers to the way a program is executed. For example, in CalcAverage(Listing 10.4.2), the avgFirstN() method is called from within the try block located in CalcAvgTest.main(). Thus, it falls within the dynamic scope of that try block.
Contrast dynamic with what you have learned about static scope, which we’ve used previously to define the scope of parameters and local variables (Figure 10.4.10). Static scoping refers to the way a program is written. A statement or variable occurs within the scope of a block if its text is actually written within that block.
Figure 10.4.10. Dynamic versus static scoping. Static scoping refers to how the program is written. Look at its definitions. Dynamic scoping refers to how the program executes. Look at what it actually does.
For example, consider the definition of MyClass(Listing 10.4.11). The variable X occurs within the (static) scope of method1(), and the variable Y occurs within the (static) scope of method2().
Listing 10.4.11. An example of dynamic versus static scoping.
A method’s parameters and local variables occur within its static scope. Also, in the MyClass definition, the System.out.println() statements occur within the static scope of method1() and method2(), respectively. In general, static scoping refers to where a variable is declared or where a statement is located. Static scoping can be completely determined by just reading the program.
Dynamic scoping can only be determined by running the program. For example, in MyClass the order in which its statements are executed depends on the result of Math.random(). Suppose that when random() is executed it returns the value 0.99. In that case, main() will call method2(), which will call System.out.println(), which will print “Hello2.” In that case, the statement System.out.println("Hello" + Y) has the following dynamic scope:
        System.out.println("Hello" + Y);
It occurs within the (dynamic) scope of method2(), which is within the (dynamic) scope of main(). On the other hand, if the result of random() had been 0.10, that particular println() statement wouldn’t have been executed at all. Thus, to determine the dynamic scope of a particular statement, you must trace the program’s execution. In fact, this is what the printStackTrace() method does. It prints a trace of a statement’s dynamic scope.

Subsection 10.4.6 Exception Propagation: Searching for a Catch Block

When an exception is thrown, Java uses both static and dynamic scoping to find a catch clause to handle it. Java knows how the program is defined—after all, it compiled it. Thus, the static scope of a program’s methods is determined by the compiler. Java also places a record of every method call the program makes on a method call stack. A method call stack is a data structure that behaves like a stack of dishes in the cafeteria. For each method call, a method call block is placed on top of the stack (like a dish), and when a particular method call returns, its block is removed from the top of the stack (Figure 10.4.12).
An important feature of the method call stack is that the current executing method is always represented by the top block on the method call stack. If an exception happens during that method call, you can trace backward through the method calls, if necessary, to find an exception handler for that exception. In Figure 10.4.12, you can visualize this back trace as a matter of reversing the direction of the curved arrows.
Figure 10.4.12. The method call stack for the Propagate program. The curved arrows give a trace of the method calls leading to the program’s present state.
In order to find a matching catch block for an exception, Java uses its knowledge of the program’s static and dynamic scope to perform a method stack trace. The basic idea is that Java traces backward through the program until it finds an appropriate catch clause. The trace begins within the block that threw the exception. Of course, one block can be nested (statically) within another block. If the exception is not caught by the block in which it is thrown, Java searches the enclosing block. This is static scoping. If it is not caught within the enclosing block, Java searches the next higher enclosing block, and so on. This is still static scoping.
If the exception is not caught at all within the method in which it was thrown, Java uses the method call stack (Figure 10.4.12) to search backward through the method calls that were made leading up to the exception. This is dynamic scoping. In the case of our CalcAvgTest() example (Listing 10.4.2), Java would search backward to the CalcAvgTest.main() method, which is where avgFirstN() was called, and it would find the catch clause there for handling IllegalArgumentException s. It would, therefore, execute that catch clause.

Exercises 10.4.7 Self-Study Exercises

1. Catches.

    Suppose a program throws an ArrayIndexOutOfBoundsException. Using the exception hierarchy in Figure 10.3.1, determine which of the following catch clauses could handle that exception.
  • catch (RunTimeException e)
  • RunTimeException is a superclass of ArrayIndexOutOfBoundsException.
  • catch (StringIndexOutOfBoundsException e)
  • This does not involve a String.
  • catch (IndexOutOfBoundsException e)
  • IndexOutOfBoundsException is a superclass of ArrayIndexOutOfBoundsException.
  • catch (Exception e)
  • The superclass Exception can catch anything!
  • catch (ArrayStoreException e)
  • Not related.

2. Exception Output.

In the program that follows suppose that the first time random() is called it returns 0.98, and the second time it is called it returns 0.44. What output would be printed by the program? What would be output if printStackTrace() were called in addition to printing an error message?
public class MyClass2 {
    public void method1(double X) {
        if (X > 0.95)
            throw new ArithmeticException(X
                      + " is out of range");
        System.out.println("Hello " + X);
    public void method2(double Y) {
        if (Y > 0.5)
             throw new ArithmeticException(Y
                      + " is out of range");
        System.out.println("Hello " + Y);
    public static void main(String argv[]) {
        MyClass2 myclass = new MyClass2();
        try {
        } catch (ArithmeticException e) {
    } // main()
  } // MyClass2

3. Exception Output 2.

In the MyClass2 program above, suppose that the first time random() is called it returns 0.44, and the second time it is called it returns 0.98. What output would be printed by the program? What would be output if printStackTrace() were called instead of printing an error message.

4. Divide by Zero Exception.

Find the divide-by-zero error in the following program, and then show what stack trace would be printed by the program:
public class BadDivide {
    public void method1 (int n) {
        method2(100, n);
    public void method2 (int n, int d) {
         System.out.println(n / d);
    public static void main(String args[]) {
        BadDivide bd = new BadDivide();
        for (int k = 0; k < 5; k++)

5. Modify Divide by Zero.

Modify method2() so that it handles the divide-by-zero exception itself, instead of letting Java handle it. Have it print an error message and a stack trace.

6. Exception Output 3.

What would be printed by the following code segment if someValue equals 1000?
int M = someValue;
try {
    System.out.println("Entering try block");
    if (M > 100)
        throw new Exception(M + " is too large");
    System.out.println("Exiting try block");
  } catch (Exception e) {
    System.out.println("ERROR: " + e.getMessage());

7. Exception Output 4.

What would be printed by the code segment in the preceding question if someValue equals 50?

8. Try/Catch Block.

Write a try/catch block that throws an Exception if the value of variable X is less than zero. The exception should be an instance of Exception and, when it is caught, the message returned by getMessage() should be “ERROR: Negative value in X coordinate.”
You have attempted of activities on this page.