previous | index | next

Step 3: Handle I/O Exceptions

Finally, modify the program so that the exception thrown when the input is the special string "ioerror" is caught by main before exiting gracefully:
    How old are you? ioerror

    This is a bogus I/O exception for testing.
    Program exiting gracefully.

This is accomplished by catching the IOException that can be thrown by the getAge calls in the main method. Note that in order to satisfy the compiler, the age variable will need to be initialized outside the try block.

The exception parameter defined in a catch clause can be used to retrieve the exception message string created when the exception was first thrown. Thus, if ex is the exception parameter, ex.getMessage() will return the message string. Also, note that the call System.exit(0) is used to exit a Java program normally.

Once main is rewritten to explicitly catch I/O exceptions, the throws clause in main's header can be eliminated.


previous | index | next