Home CPSC 240

Lab 3: Catching Exceptions



To practice catching and dealing with exceptions


Checked and Unchecked Exceptions

In Java, some exceptions are unchecked meaning that if you don't catch them, your code will still compile.

Others, however, are checked meaning that you must signify how your code deals with a possible exception. There are two ways you can deal with your code when there is an unchecked exception in it:

  1. Signify that your method throws the exception. That means that you will just propagate the exception up to whoever called it to deal with. To do this, you would add the "throws" message to the end of your method line.
  2. Catch the exception and handle it appropriately. This means your method takes care of its own problems, and won't leak exceptions up to the caller. To do this, you would put the catch message after the code where the exception can originate from.

The second option is better, when possible.



For this lab, you will modify Sum.java program which opens a file called data.txt, and adds up all of the integers in the file and reports the sum.

This program does not compile because of an unchecked FileNotFoundException. You could fix this error by marking that main throws this type of exception, but it will be better to catch it instead.

Put the code that opens the file in a try block. Then put in a catch block to handle the FileNotFoundException. In the case when the file isn't found, your program should report that the input file was not found and exit.

This program also can produce an InputMismatchException. This is not a checked exception, so the program will compile if you ignore this. The problem is that it will not run properly because the input file has some words in it. When you try to read a number but actually get a word, an InputMismatchException is thrown. You should catch this exception too. In these cases, you should just not count these entries in the file towards the sum.





When you are done, please submit the Java code under the assignment in Canvas.



A solution to this lab can be found in Sum.java.

Copyright © 2023 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.