Exception Handling Example

The classes linked off this page illustrate exception handling. The SumLines class reads lines from a file and sums the numbers on those lines. It handles two types of exceptions:

  1. FileNotFoundException: If the file entered on the command line does not exist, then a catch statement in main prompts the user for another file name. If this filename does not work, the program throws the FileNotFoundException out of main and terminates. FileNotFoundException is a pre-defined java exception and is thrown when you try to open a new file.

  2. BadNumberException: This exception is user-defined and is thrown when a non-positive integer is read. It is handled by printing the bad number and an error message.

The Source Files