Chapter 11 - Exceptions: When Things Go Wrong ... And They Will!
|
Chapter Objectives:
-
Understand Java's exception handling mechanisms.
-
Be able to use the Java try/catch statement.
-
Know how to design effective exception handlers.
-
Be able to design your own Exception subclasses.
-
Appreciate the importance that exception handling plays in program design.
-
Understand the computational overhead of exception handling.
|
Index:
|
Introduction
-
No matter how well designed a program is, there is always the chance that
some kind of error will arise during its execution.
-
A well-designed program should include code to handle errors and other
exceptional conditions when they arise.
-
This chapter describes Java's exception handling features.
-
Java exceptions are events that occur when the Java engine has determined
that your program has done something illegal or when your program tries
to do something that won't work.
-
Exceptions are objects that Java "throws" back to your program. If
your program is not written to "catch" them, then the Java engine terminates
your program and spews a bunch of error messages to the screen.
-
Obviously, its better for your program to catch and handle these exceptions
rather than have itself aborted (potentially leaving all sorts of files
and databases in an undetermined state).
-
Also, its best to write good code that will not generate an exception (though
sometimes you don't have control of that).
-
Some Java classes that you will be using (IO and SQL) require you to catch
exceptions that they may produce.
-
Types of actions that can cause exceptions:
-
Trying to read a file that does not exist
-
Trying to save to a disk that is full or trying to save without access
-
Dividing by zero
-
Trying to convert a string to a numeric, when the string contains bad characters
-
Accessing an array item that does not exist (index out of bounds)
-
Example: Figure 11-1 code that could generate a divide by zero:
/**
* Precondition: N > 0
* Postcondition: intAverage() equals the integer average of the
* array's first N (N > 0) elements
*/
public int intAverage(int arr[], int N) {
int avg = 0;
for (int k = 0; k < N; k++)
avg += arr[k];
avg = avg / N;
// WHAT IF N is 0 ??
return avg;
} // intAverage()
Handling Errors
-
Traditional error handling
-
Add program statements to test for error conditions
-
Requires the programmer to anticipate and react to every possible error
-
Programmer must decide what to do:
-
Return an error code back to the invoking method
-
This may not be possible (or easy) for methods that return data values,
as in the example below
-
Popup an error message and abort the program
-
Do this if the error is "unfixable"
-
Write an error message to a log file
-
Fix the error and continue (may require using a default value or asking
the user to re-enter a value)
-
Ignore the error
-
In any case, the system, which may include files and databases, must be
left in a valid (uncorrupt state).
-
Corrupt could mean leaving database records locked
-
Losing transactions or performing part of a transaction
-
Cluttering the drive with temporary files
-
Leaving partial or broken data files.
-
Example:
public int intAverage( int arr[], int N ) {
int avg = 0;
if (N <= 0) {
System.out.println("ERROR
intAverage: Can't average 0 items");
System.out.println("ERROR
intAverage: " +
" Program terminating abnormally");
System.exit(0);
}
for (int k = 0; k < N; k++)
avg += arr[k];
avg = avg / N;
// At this point, N > 0
return avg;
} // intAverage()
-
Trying, Throwing and Catching Exceptions
-
Default Exception Handling
-
Java can handle unchecked exceptions itself
-
it merely prints the exception message to the terminal and displays the
contents of the method call stack.
-
the method call stack consists of the name of each method that was invoked
and the line number where the exception or call was made.
-
the contents of the method call stack is a valuable debugging aid to the
programmer.
-
of course, this may leave your system in a corrupt state, not to mention
annoying your users.
-
click here for the source to a short program
that demonstrates an exception handled by Java and one caught. You can
save it as ExceptionDemo.java, then compile and run it.
Class |
Description |
ArithmeticException |
Division by zero or some other kind of arithmetic problem |
ArrayIndexOutOfBoundsException |
An array index is less than zero or greater than or equal to the
array's length |
FileNotFoundException |
Reference to a unfound file |
IndexOutOfBoundsException |
An array or string index out of bounds |
NullPointerException |
Reference to an object which has not been instantiated |
NumberFormatException |
Use of an illegal number format, such as when calling a method |
StringIndexOutOfBoundsException |
A String index less than zero or greater than or equal
to the String's length |
IllegalArgumentException |
Calling a method with an improper argument |
Table 11-1 Some Important Java Exceptions
Checked Exceptions
-
Checked exception: must either be caught or declared within the method
where it is thrown.
-
Monitored by the Java compiler. If you don't catch them or declare that
your method will throw them, then the compiler will give you an error.
-
Example: IOException, here main does not use a try/catch, instead it just
declares that it will throw them.
public static void main(String argv[]) throws IOException
{
Unchecked Exceptions
-
Unchecked exceptions: belong to a subclass of RuntimeException.
-
Not monitored by the compiler.
-
You can choose to not to handle them at the risk of having your program
abort and data lost.
Robust Programming
Kind of Exception |
Kind of Program |
Action to be Taken |
Caught by Java |
|
Let Java handle it |
Fixable condition |
|
Fix the error and resume execution |
Unfixable condition |
Stoppable |
Report the error and terminate the program |
Unfixable condition |
Not Stoppable |
Report the error and resume processing |
-
Your own programs: letting Java handle exceptions may be the best
choice.
-
During program development: exceptions help you identify bugs.
-
Commercial software: the program should handle its exceptions because
the user can’t.
-
Handling Strategies
-
Print Error Message and Terminate. Unless the error can be fixed, it’s
better to terminate a program than to allow it to spread bad data -- e.g.,
the divide-by-zero example.
-
Log the Error and Resume: A heart monitor program cannot be terminated.
-
Fix the error and resume - print an error message and allow the user to
retry the operation.
-
Effective Design: Exceptions should not be used to handle routine conditions.
-
For example, if an array is routinely overflowed, use a Vector instead.
-
JOptionPane covered in
Chapter 9 notes provides an easy mechanism to popup error messages
and to ask the user for input responses.
Summary
Key Technical Terms: catch block, catch an exception,
checked exception,dialog box, error dialog , exception, exception
handler, finally block, method stack trace, throw an exception, try
block, unchecked exception
Suggested Exercises: 1, 2, 3, 4, 6, 9,10, 12, 13,
14