Exceptions |
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.
Note that the catch clause has the phrase Exception e in parentheses just like parameter list for a method. It essentially is. So:
It would be good to associate different "bunches of statements" with different error conditions. We can use specialized Exception classes to catch only certain types of exceptions. In our case, NumberFormatException for invalid characters in the text field, and IllegalArgumentException for color values out of 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 |