Required: These notes!
Recommended: Java in a Nutshell, pp. 56-59, 68.


We are continuing to cover the Java's exception/error handling mechanism. The previous lesson described the difficulties inherent in handling errors in programs, described the basic of Java's mechanism for error handling, and brought us as far as the class hierarchy (rooted at the class Throwable) of exceptions in the Java API. In this class, we will see more fully how inheritance, polymorphism and object-oriented design combine to provide a flexible, extensible, and relatively easy to use mechanism for handling errors and exceptional considtions.

What you get for free from inheritance

You should look at the Java API documentation for class Throwable. There are a few methods you get from Throwable that are really important:

Using just the different messages, we can easily produce meaningful error messages ... at least for some errors.

~/$ java Ex1
Error in program Ex1: Couldn't convert input to array of ints
~/$ java Ex1 2,three,4
Error in program Ex1: Couldn't convert input to array of ints
~/$ java Ex1 2,0,3
Error in program Ex1: Zero value in array B!
~/$ java Ex1 -2,-1,3
Error in program Ex1: Sum is negative, cannot take sqrt!
Note: We could ad a verbose mode to our program in which errors would result in a stack trace being printed.

Adding to the exception hierarchy to organize better

We might decide that we need to handle exceptions generated by SpecialFunc differently than exceptions generated by other parts of the program. Perhaps main simply wants to preface each error message with whether or not it came from SpecialFunc or from Ex1? In order to do this cleanly we need to define a new exception type specifically for our SpecialFunc class. This way, SpecialFunc.compute() can throw this new type instead of a generic Throwable, which allows main to catch those exceptions separately from any others.

Extending functionality:

Suppose we want to be able to specify exactly which element in the comma-separated list could not be converted? Suppose we wanted to include the index of of the integer that was zero? We need exceptions that carry extra information with them! In other words, we need to start using inheritance to extend functionality.

~/$ java Ex2
Error! An argument is required.
~/$ java Ex2 2,,3
Error! Could not convert input '' to an integer!
~/$ java Ex2 2,six,3
Error! Could not convert input 'six' to an integer!
~/$ java Ex2 2,0,3
Error 'Zero value' with input value 1
~/$ java Ex2 2,0,3
Error 'Zero value' with input at index 1
~/$ java Ex2 2,-1,3
Negative sum, can't take root.
~/$ java Ex2 ,
Bad stuff happened!