Exceptions |
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: Warning 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.
Note that the catch clause has the phrase Exception e in parentheses just like parameter list for a method. It essentially is. So:
Demo: Almost Intelligible Label Color Mixer
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.
This is a sketch of what the code of the Color constructor looks like:
public Color ( int r, int g, int b ) { if ( r < 0 || r > MAXVALUE ) throw new IllegalArgumentException("Color value out of range- Red"); if ( g < 0 || g > MAXVALUE) throw new IllegalArgumentException("Color value out of range- Green"); if ( b < 0 || b > MAXVALUE) throw new IllegalArgumentException("Color value out of range- Blue"); this.r = r; this.g = g; this.b = b; }
So the throw keyword is used to accomplish this. The program should construct a new Exception of the appropriate type and throw it. If the code is operating inside of a try statement somewhere, the exception delivered at a matching catch clause if there is one.
Exceptions |