13. Exceptions: When Things Go Wrong

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

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 (Fig. 10.6).

We will discuss try blocks, which typically

are associated with catching exceptions, later in the section.

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 han- dler 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 Figure 10.7 mimics

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 10.7: In this version of the calcAvgTest program, an Illegal- ArgumentException thrown in CalcAverage.avgFirstN(), would be handled by the catch clause in CalcAvgTest.main().

 

 

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.

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:

,,

 

J

Note the syntax of the throw statement. It creates a new Illegal- ArgumentException object and passes it a message that describes the error. This message becomes part of the exception object. It can be re- trieved using the getMessage() method, which is inherited from the Throwable class (Fig. 10.4).

When a throw statement is executed, the JVM interrupts the normal ex- ecution of the program and searches for an exception handler. We will de-

 

scribe the details of this search shortly. In this case, the exception handler is the catch clause contained in the CalcAvgTest.main() method:

,,

 

 

 

J

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 sec- ond statement uses the printStackTrace() method, which is defined in Throwable and inherited by all Exceptions, 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:

,,

 

 

 

 

 

 

 

 

J

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 illus- trative 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:

,,

 

 

 

 

Second, we provide one or more catch clauses to handle par- ticular types of exceptions. In this case, we are only handling IllegalArgumentExceptions.

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 (Fig. 10.8).


J

 

 

 

 

 

Responding to the fire alarm

 

 

 

Figure 10.8: Playing catch: In this design, the Illegal- ArgumentException is thrown by the CalcAverage.avg- FirstN() method and caught by the catch clause within CalcAvgTest.main() method.

 

 

 

 

 

Separating Error Checking from Error Handling

As we see in the CalcAvgTest example, an important difference be-

tween Java’s exception handling and more traditional approaches is that Divide and conquer

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 throws IllegalArgumentException 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 han- dle other errors of that type. For example, this catch clause could handle all IllegalArgumentExceptions 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.

 

 

 

The try block

 

 

The catch block


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 Fig- ure 10.9. The try block is meant to include a statement or statements that

,,

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 10.9: Java’s try/catch statement.

 

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, includ- ing 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, Normal flow of execution

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 kindExceptional flow of execution

of exception that was thrown. Exceptions are thrown by using the throw

statement, which takes the following general form:

,,

 

J

The keyword throw is followed by the instantiation of an object of the ExceptionClassName class. This is done the same way we instanti- ate 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:

,,

 

 

 

 

A catch block is very much like a method definition. It contains a param- eter, 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 Fig. 10.4). A thrown exception will match any parameter of its own class or any of its superclasses. Thus, if an ArithmeticExcep- tion is thrown, it will match both an ArithmeticException parame- ter 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.4). 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 hid- den by the more general one. You might as well just not have the more specific clause at all.


J

 

 

 

 

Exceptions are objects

 

 

 

 

 

 

 

Arranging catch clauses

 

To illustrate how to arrange catch clauses, suppose an Arithmetic- Exception is thrown in the following try/catch statement:

,,

 

 

 

 

 

 

J

In this case, the exception would be handled by the more specific

 

 

Which handler to use?


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.

 

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 belong- ing 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.

 

 

 

 

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() (Fig. 10.7) 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 scope

Dynamic scoping refers to the way a program is executed. For ex- ample, in CalcAverage (Fig. 10.7), 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 lo- Static scope

cal variables (Fig. 10.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. For example, consider the def- inition of MyClass (Fig. 10.11). The variable X occurs within the (static) scope of method1(), and the variable Y occurs within the (static) scope of method2().

Figure 10.10: Dynamic versus static scoping. Static scoping refers to how the program is writ- ten. Look at its definitions. Dy- namic scoping refers to how the program executes. Look at what it actually does.

 

 

 

 

 

 

 

 

A method’s parameters and local variables occur within its static scope. Also, in the MyClass definition, the System.out.println() state- ments occur within the static scope of method1() and method2(), re- spectively. In general, static scoping refers to where a variable is de- clared 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 de- pends 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

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 10.11: An example of dynamic versus static scoping.

 

“Hello2.” In that case, the statement System.out.println("Hello"

+ Y) has the following dynamic scope:

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

Method call stack


J

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.

Exception Propagation: Searching for a Catch Block

When an exception is thrown, Java uses both static and dynamic scop- ing 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 (Fig. 10.12).

An important feature of the method call stack is that the current ex- ecuting 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 han- dler for that exception. In Figure 10.12, you can visualize this back trace as a matter of reversing the direction of the curved arrows.

 

 

public class Propagate{

public void method1 (int n) { method2(n);

}

public void method2 (int n) { method3(n);


Method Call Stack The state of the stack on the first iteration of the

for loop in method3().


Figure 10.12: The method call stack for the Propagate pro- gram. The curved arrows give a trace of the method calls leading to the program’s present state.

 

}

public void method3 (int n) {

for(int k=0; k<5; k++) { //Block1 if(k % 2==0) {//Block2

System.out.println(k/n) ;

}

}

}

public static void main(String args[]) { Propagate p=new propagate() ; p.method1(0) ;

}

}

 

 

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 Method stack trace

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 (Fig. 10.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 (Fig. 10.7), 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 IllegalArgumentExceptions. It would, therefore, execute that catch clause.

 

 

 

SELF-STUDY EXERCISES

 

EXERCISE 10.3 Suppose a program throws an ArrayIndexOutOf- BoundsException. Using the exception hierarchy in Figure 10.4, de- termine which of the following catch clauses could handle that exception.

 

catch (RunTimeException e)

catch (StringIndexOutOfBoundsException e)

catch (IndexOutOfBoundsException e)

catch (Exception e)

catch (ArrayStoreException e)

 

EXERCISE 10.4 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?

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

 

 

 

 

EXERCISE 10.5 For the values returned by random() in the previ- ous exercise, show what would be output if printStackTrace() were called in addition to printing an error message.

 

 

 

 

EXERCISE 10.6 In the MyClass2 program, 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?

 

 

 

 

EXERCISE 10.7 For the values returned by random() in the previ- ous exercise, show what would be output if printStackTrace() were called instead of printing an error message.

 

EXERCISE 10.8Find the divide-by-zero error in the following pro- gram, and then show what stack trace would be printed by the program:

,,

 

 

 

 

 

 

 

 

 

J

 

EXERCISE 10.9 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.

 

EXERCISE 10.10 What would be printed by the following code seg- ment if someValue equals 1000?

,,

 

 

 

 

 

 

J

 

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

EXERCISE 10.12 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.”