Exceptions |
[Only cover first 4 sections of this chapter now. Other parts will come when we talk about streams.]
We have seen exceptions all semester long:
These are just a few examples of a more general system provided by Java (and some other programming languages) to deal with errors called exceptions.
We will look at what exceptions can do for us and how Java implements them using variants of this Color Mixer program covered earlier:
Demo: Color Mixer
In this simple version, things work fine, until we enter non-numerical text. When this is passed to Integer.parseInt, a NumberFormatException is thrown.
Demo: Safer Color Mixer
The isInteger method verified the correct contents, but there's also code to make sure the value is between 0 and 255, the valid range for the RGB values of a color.
Demo: Fragile Color Mixer
When we run this and give invalid input, Java notices the problem and "throws" an exception. We see this as the huge mess of error messages, but the start of that mess says there was a NumberFormatException when we put non-numeric characters in a text field, or IllegalArgumentException if we type a number that's out of the 0-255 range.
The computer didn't break and our program didn't even crash. Clearly, Java is doing these same kinds of error checks we were doing, and hopefully doing a more thorough job than us.
try { bunches of statements } catch { bunches of statements }
The idea is that the "bunch of statements" in try might throw an exception, and if it does, some code in the "bunch of statements" in catch can respond to it.
Demo: Almost Intelligible Label Color Mixer
Here, we create a Swing JLabel that can be displayed when an error is detected. The catch clause now has a statement to add this JLabel to the window.
There are two things here we haven't seen before - the remove method is used to remove an Swing component that may previously have been added. And validate shuffles things around and redisplays them nicely in the case where a component was added or removed.
The message for a value out of range is now pretty good. However, the message for the invalid input isn't very informative. Plus, while we have detected the errors, we haven't responded to them in any useful way, like the way we took values that were too high or too low and forced them back into the 0-255 range.
Exceptions |