13. Exceptions: When Things Go Wrong

13.5. Error Handling and Robust Program Design

An important element of program design is to develop appropriate ways of handling erroneous and exceptional conditions. As we have seen, the JVM will catch any unchecked exceptions that are not caught by the pro-

gram itself. For your own (practice) programs, the best design may sim- Let Java do it?

 

ply be to use Java’s default exception handling. The program will termi- nate when an exception is thrown, and then you can debug the error and recompile the program.

On the other hand, this strategy would be inappropriate for commercial software, which cannot be fixed by its users. A well-designed commercial program should contain exception handlers for those truly exceptional conditions that may arise.

In general there are three ways to handle an exceptional condition that isn’t already handled by Java (Table 10.3). If the exceptional condition

 

TABLE 10.3 Exception-handling strategies.

 

Kind of Exception

Kind of Program

Action to Be Taken

Caught by Java Fixable condition Unfixable condition

 

 

Stoppable

Let Java handle it

Fix the error and resume execution Report the error and terminate

the program

Unfixable conditionNot stoppableReport the error and resume

processing

 

 

 

What action should we take?


cannot be fixed, the program should be terminated, with an appropriate error message. Second, if the exceptional condition can be fixed without invalidating the program, then it should be remedied and the program’s normal execution should be resumed. Third, if the exception cannot be fixed, but the program cannot be terminated, the exceptional condition should be reported or logged in some way, and the program should be resumed.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Program development


Print a Message and Terminate

Our illegal argument example is a clear case in which the exception is best handled by terminating the program. In this case, this particular error is best left to Java’s default exception handling, which will terminate the program when the exception is thrown. There is simply no way to satisfy the postcondition of the avgFirstN() method when N is less than or equal to 0. This type of error often calls attention to a design flaw in the

 

program’s logic that should be caught during program development. The throwing of the exception helps identify the design flaw.

Similar problems can (and often do) arise in connection with errors that are not caught by Java. For example, suppose that your program receives an erroneous input value, whose use would invalidate the calculation it

is making. This won’t be caught by Java. But it should be caught by Don’t spread bad data!

your program, and an appropriate alternative here is to report the error and terminate the program. Fixing this type of error may involve adding routines to validate the input data before they are used in the calculation. In short, rather than allowing an erroneous result to propagate through-

out the program, it is best to terminate the program.

 

 

Log the Error and Resume

Of course, the advice to stop the program assumes that the program can be terminated reasonably. Some programs—such as programs that monitor the space shuttle or programs that control a nuclear magnetic resonance (NMR) machine—cannot (and should not) be terminated because of such an error.

Such programs are called failsafe because they are designed to run with- out termination. For these programs, the exception should be reported in whatever manner is most appropriate, but the program should continue running. If the exceptional condition invalidates the program’s computa- tions, then the exception handler should make it clear that the results are tainted.

Other programs—such as programs that analyze a large transaction


 

 

 

Failsafe programs

 

database—should be designed to continue processing after catching such Programs that can’t be stopped

errors. For example, suppose the program a large airline runs a program once a day to analyze the ticketing transactions that took place. This kind of program might use exceptions to identify erroneous transactions or transactions that involve invalid data of some sort. Because there are bound to be many errors of this kind in the database, it is not reason- able to stop the program. This kind of program shouldn’t stop until it has finished processing all of the transactions. An appropriate action for this kind of program is to log the exceptions into some kind of file and continue processing the transactions.

Suppose a divide-by-zero error happened in one of these programs. In that case, you would override Java’s default exception handling to ensure that the program is not terminated. More generally, it’s important that

 

these types of programs be designed to catch and report such exceptions. This type of exception handling should be built right into the program’s design.

 

 

 

Problem statement

 

 

 

 

 

 

 

 

IntField

 

+IntField()

+IntField(in size : int)

+getInt() : int

 

 

Figure 10.13: An IntField is a JTextField that accepts only in- tegers.


Fix the Error and Resume

As an example of a problem that can be addressed as the program runs, consider the task of inputting an integer into a text field. As you have probably experienced, if a program is expecting an integer and you at- tempt to input something beside an integer, a NumberFormatException is generated and the program will terminate. For example, if you enter “$55” when prompted to input an integer dollar amount, this will gen- erate an exception when the Integer.parseInt() method is invoked. The input string cannot be parsed into a valid int. However, this is the kind of error that can be addressed as the program is running.

Let’s design a special IntField that functions like a normal text field but accepts only integers. If the user enters a value that generates a NumberFormatException, an error message should be printed and the user should be invited to try again. As

Figure 10.13 shows, we want this special field to be a subclass of JTextField and to inherit the basic JTextField functionality. It should have the same kind of constructors that a normal JTextField has. This leads to the definition shown in Figure 10.14.

,,

 

 

 

 

 

 

 

 

 

 

J

Figure 10.14: A NumberFormatException might be thrown by the

Integer.parseInt() method in IntField.getInt().

 

 

 

What constructors do we need?


Note that the constructor methods use super to call the JTextField constructor. For now, these two constructors should suffice. However, later we will introduce a third constructor that allows us to associate a bound with the IntField later in this chapter.

 

Our IntField class needs a method that can return its contents. This

method should work like JTextField.getText(), but it should re- What methods do we need?

turn a valid integer. The getInt() method takes no parameters and will return an int, assuming that a valid integer is typed into the IntField. If the user enters “$55,” a NumberFormatException will be thrown by the Integer.parseInt() method. Note that getInt() declares that it throws this exception. This is not necessary because a NumberFormatException is not a checked exception, but it makes the code clearer.

Where and how should this exception be handled? The exception can- not easily be handled within the getInt() method. This method has to return an integer value. If the user types in a non-integer, there’s no way to return a valid value. Therefore, it’s better just to throw the exception to the calling method, where it can be handled more easily.

In a GUI application or applet, the calling method is likely to be an

actionPerformed() method, such as the following:

,,

 

 

 

 

 

 

 

 

 

The call to getInt() is embedded in a try/catch block. This leads to the design summarized in Figure 10.15. The IntField throws an exception that is caught by the GUI, which then displays an error message.

 

 

 

showMessageDialog()


J

 

 

 

Figure 10.15: If the user types a non-integer into an IntField, it will throw a NumberFormatException. The GUI will display an error message in a JOptionPane (a dialog window).

 

 

If the user inputs a valid integer, the program will just report a mes- sage that displays the value. A more real-world example would make a more significant use of the value. On the other hand, if the user types an erroneous value, the program will pop up the dialog box shown in Figure 10.16. (See the “From the Library” section of this chapter for more on dialog boxes.) When the user clicks the OK button, the program will resume normal execution, so that when an exception is raised, the enter value is not used, and no harm is done by an erroneous value. The user

 

Figure 10.16: This exception han- dler opens a dialog box to display an error message.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Defensive design: Anticipating an


 

can try again to input a valid integer. Note that the finally clause repaints the GUI. In this case, repainting would display the appropriate message on the applet or the application.

This is an example of what we might call defensive design. Defensive de- sign is when we anticipate a possible input error and take steps to ensure

 

exceptionthat a bad value is not propagated throughout the program.

 

 

 

 

 

 

 

Anticipating exceptions


Admittedly, the sense in which the error here is “fixed” is simply that the user’s original input is ignored and reentered. This is a legitimate and simple course of action for this particular situation. It is far prefer- able to ignoring the exception. If the program does not handle this excep- tion itself, Java will catch it and will print a stack trace and terminate the program. That would not be a very user-friendly interface!

Clearly, this is the type of exceptional condition that should be antici- pated during program design. If this happens to be a program designed exclusively for your own use, then this type of exception handling might be unnecessary. But if the program is meant to be used by others, it is im- portant that the program be able to handle erroneous user input without crashing.

 

 

 

To Fix or Not to Fix

Let’s now consider a problem where it is less clear whether an excep- tion can be successfully fixed “on the fly.” Suppose you have a program that contains an array of Strings, which is initially created with just two elements.

,,

 

J

If an attempt is made to add more than two elements to the array, an ArrayIndexOutOfBoundsException will be raised. This exception can be handled by extending the size of the array and inserting the ele- ment. Then the program’s normal execution can be resumed.

To begin creating such a program, let’s first design a method that will

insert a string into the array. Suppose that this is intended to be a private Problem statement

method that will only be used within the program. Also, let’s suppose that the program maintains a variable, count, that tracks how many values have been stored in the array. Therefore, it will not be necessary to pass the array as a parameter. So, we are creating a void method with one parameter, the String to be inserted:

,,

 

 

 

 

 

The comment notes where an exception might be thrown.

Can we handle this exception? When this exception is raised, we could create a new array with one more element than the current array. We could copy the old array into the new array and then insert the String in the new location. Finally, we could set the variable list, the array refer- ence, so that it points to the new array. Thus, we could use the following try/catch block to handle this exception:

,


J

 

 

Algorithm design

 

 

,

 

 

JPanel

 

 

 

 

 

 

 

J

The effect of the catch clause is to create a new array, still referred to as

list, but that contains one more element than the original array.

 

Figure10.17:The FixArrayBound class uses exception handling to extend the size of an array each time a new

 

Note the use of the finally clause here. For this problem it’s impor- tant that we increment count in the finally clause. This is the only way to guarantee that count is incremented exactly once whenever an element is assigned to the array.

The design of the FixArrayBound class is shown in Figure 10.17. It provides a simple GUI interface that enables you to test the insertString() method. This program has a standard Swing interface, using a JFrame as the top-level window. The program’s components are contained within a JPanel that’s added to the JFrame in the main() method.

Each time the user types a string into the text field, the action- Performed() method calls the insertString() method to add the string to the array. On each user action, the JPanel is repainted. The paintComponent() method simply clears the panel and then displays the array’s elements (Fig. 10.18).

 

 

 

 

 

Poor program design

 

 

 

 

 

 

 

 

 

Proper array usage

 

 

 

 

 

 

Figure 10.18: The strings dis- played are stored in an array that is extended each time a new string is entered.


The complete implementation of FixArrayBound is given in Fig- ure 10–19. This example illustrates how an exception can be handled suc- cessfully and the program’s normal flow of control resumed. However, the question is whether such an exception should be handled this way.

Unfortunately, this is not a well-designed program. The array’s initial size is much too small for the program’s intended use. Therefore, the fact that these exceptions arise at all is the result of poor design. In general, exceptions should not be used as a remedy for poor design.

 

JAVA EFFECTIVE DESIGN

Truly Exceptional Conditions. A

well-designed program should use exception handling to deal with truly exceptional conditions, not to process conditions that arise under normal or expected circumstances.

 

For a program that uses an array, the size of the array should be chosen so that it can store all the objects required by the program. If the program is some kind of failsafe program, which cannot afford to crash, then some- thing like the previous approach might be justified, provided this type of exception occurs very rarely. Even in that case it would be better to generate a message that alerts the program’s user that this condition has occurred. The alert will indicate a need to modify the program’s memory requirements and restart the program.

 

,,

import j ava . awt . ;

import j ava . awt . event . ;

import j avax . swing . ;

public c l a s s FixArrayBound extends JPanel

implements Action Listener public s t a t i c f i n a l in t WIDTH = 350 , HEIGHT = 1 0 0 ; private J T e x t F i e l d i n F i e l d = new J T e x t F i e l d ( 1 0 ) ;

private JLabel prompt = new JLabel (

Input a word and type <ENTER>: ” ) ;

// I n i t i a l l yl i s t h a s 2 e l e m e n t s

private S t r i n g l i s t [ ] = new S t r i n g [ 2 ] ;

private in t count = 0 ;

 

publicFixArrayBound ( )

i n F i e l d . add Action Listener ( t h i s ) ; add ( prompt ) ;

add ( i n F i e l d ) ;

s e t S i z e (WIDTH, HEIGHT ) ;

} // F i x A r r a y B o u n d ( )

public void paintComponent ( Graphics g )

g . set Color ( getBackground ( ) ) ;// C l e a r t h e b a c k g r o u n d

g . f i l l R e c t ( 0 , 0 , WIDTH, HEIGHT ) ;

g . set Color ( getForeground ( ) ) ; S t r i n g tempS = ”” ;

for ( in t k = 0 ; k < l i s t . length ; k++) tempS = tempS +l i s t [ k ] + ;

g . drawString ( tempS , 10 , 5 0 ) ;

} // p a i n t C o m p o n e n t

private void i n s e r t S t r i n g ( S t r i n g s t r )

t r y

l i s t [ count ] = s t r ;

catch ( ArrayIndexOutOfBoundsException e )

S t r i n g newList [ ] = new S t r i n g [ l i s t . length + 1 ] ; // New a r r a y

for ( in t k = 0 ; k < l i s t . length ; k++) // Co p y o l d t o new

newList [ k ] = l i s t [ k ] ;

newList [ count ] = s t r ; // I n s e r t i t e m i n t o new

l i s t = newList ;// Make o l d p o i n t t o new

f i n a l l y// T h e e x c e p t i o n i s now f i x e d

count ++;//s o i n c r e a s e t h e c o u n t

}

} // i n s e r t S t r i n g ( )

public void action Performed ( ActionEvent evt ) i n s e r t S t r i n g ( i n F i e l d . get Text ( ) ) ;

i n F i e l d . s e t T e xt ( ”” ) ; r e pa int ( ) ;

// a c t i o n P e r f o r m e d ( )

\J

Figure 10.19: FixArrayBound increases the size of the array when a

ArrayIndexOutOfBoundsException is raised.

 

,,

 

 

 

 

 

 

 

 

 

J

Figure 10.19: (continued) FixArrayBound increases the size of the array when ArrayIndexOutOfBoundsException is raised.

 

 

 

 

Choosing the correct data structure

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Exception

 

+getMessage()

 

 

IntOutOfRangeException


If it is not known in advance how many objects will be stored in an array, a better design would be to make use of the java.util.Vector class (see “From the Java Library” in Chapter 9). Vectors are designed to grow as new objects are inserted. In some ways the exception-handling code in our example mimics the behavior of a vector. However, the Vector class makes use of efficient algorithms for extending its size. By contrast, exception-handling code is very inefficient. Because exceptions force the system into an abnormal mode of execution, it takes considerably longer to handle an exception than it would to use a Vector for this type of application.

 

 

SELF-STUDY EXERCISE

EXERCISE 10.13 For each of the following exceptions, determine whether it can be handled in such a way that the program can be resumed or whether the program should be terminated:

A computer game program detects a problem with one of its GUI ele- ments and throws a NullPointerException.

A factory assembly-line control program determines that an important

control value has become negative and generates an Arithmetic- Exception.

A company’s Web-based order form detects that its user has entered an invalid String and throws a SecurityException.

 

SECTION 10.6 Creating and Throwing Your Own Exceptions487