go to previous page   go to home page   go to next page        


Possibly not. The program could be written using ordinary logic. Using exceptions is probably a needless complication.

When to Throw an Exception

Exceptions should be used for exceptional situations outside of the normal logic of a program. In the example program an out of range value is likely to be fairly common and should be dealt with using normal if-else type logic. (See the programming exercises.)

Another situation where throwing an exception is appropriate is when the problem occurs in the middle of a complicated method that would be made even more complicated if it also had to handle unexpected data. It might throw an exception in order to "give up" and go back to the caller (or to a catch{} block at the end of the method).

It is not always obvious when an exception is appropriate. Books on Object Oriented Software Design devote much space on the matter. A large, commercial-quality application program must be consistent in its use of exceptions and in exception handling. Decisions cannot be made on a method-by-method basis.


The exception was thrown and constructed by:

throw new Exception("Age is: " + age );

If the method that catches this exception uses the exception's getMessage() method, what does it get?