Exceptions |
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.
Exceptions |