CS 051 Fall 2011

Lecture 33

Exceptions

Exceptions in Java:

When a problem occurs, the current method may not know how serious it is. Should the program be
terminated? Or should a default value be used? It is also possible that this decision would be
easier to make for the calling method, since it knows what behavior was expected, or how the
return value was going to be used. Exceptions allow the programmer to handle the problem in
appropriate place.

In the class example ColorMixer with Warning Label, we saw
how we could give the user a warning if the inputs to the program were not valid.
This approach worked, but was fairly simplistic. We did not differentiate between what kinds
of problems could be encountered, or how the user could handle it.

In the class example AlmostIntelligibleColorMixer, we used the
exception's getMessage() method to return a more useful message to the user. This worked
well for the case where the color value was out of range, but not really well for when we tried
to convert a non-numeric string to an integer.

In the class example IntelligibleColorMixer, we used multiple
catch blocks, one for each type of exception that we expected for our inputs. This
allowed us to write a more descriptive warning for the user when a non-numeric string was
entered, but keep the useful message for when the color value was just out of range.

Since exceptions are objects, their classes can extend other exception classes.
All exceptions are subclasses of the Exception class. This is important because the
catch block will catch all exceptions of the given type, plus any exceptions that are
subclasses of the given type.

We finished with the class example ExceptionalStringDemo, which illustrated
many of the points discussed above.