Working with Exceptions
What can go wrong when reading a file, and how `try...catch` and try-with-resources keep your application from crashing.
Apprentice · Java · Updated
If you want to read the contents of a file, the Java runtime needs to open the file as a stream (a FileInputStream). We then read that stream into our application with a Scanner.
There are various things that can go wrong when attempting to read a file.
- The file may not exist.
- The file may be locked.
- We may not have the permissions to open or read the file.
These are all things that we cannot control, and could cause our application to crash. This is called a runtime error.
Java uses the Exception Handling model to deal with runtime errors.
Many runtime errors can be avoided with some simple if-else logic.
- Integer division by zero - check if the denominator is 0 before doing the math
- Array index out of bounds - verify the length of an array before trying to read an invalid value.
But some errors cannot be avoided with an if statement. This is where a try...catch block is useful.
When the Java runtime encounters an error, it stores error details into an Exception object and throws the exception. If we do not catch the exception, the application will crash.
File file = new File("bad-file.txt");
try
{
// try to open a file that doesn't exist
Scanner reader = new Scanner(file);
// if the file does not exist, this line of code will not execute
reader.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
Java 7 introduced an update to the try...catch block. It is called try with resources. The concept is that any resource that is defined as part of the try block will automatically close when the try block is completed, even if an exception was thrown.
File file = new File("bad-file.txt");
try (Scanner reader = new Scanner(file))
{
// no need to call reader.close()
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
Opening a file can throw a FileNotFoundException, so Java requires you to catch it in a try...catch block (or declare it with throws).
Do it: read a quantity without crashing
The coffee shop's orders come in a file, one line per order, and each line has the quantity as text. Most say 3 or 12, but now and then someone typed three, or left the box empty. Turning text into a number is Integer.parseInt: Integer.parseInt("3") gives 3, but Integer.parseInt("three") throws a NumberFormatException, and the whole app crashes on one bad line.
The starter calls Integer.parseInt with no protection, so the tests with a bad quantity crash it. Catch the exception instead, and treat a quantity that can't be read as 0, so that line orders nothing and the app carries on.
The method gets one value:
text: the quantity, as it was read from the file.
For example:
text |
Integer.parseInt(text) |
Returns |
|---|---|---|
"3" |
gives 3 |
3 |
"three" |
throws a NumberFormatException |
0 |
So quantityOf("3") returns 3, and quantityOf("three") returns 0.
Your job: change the method quantityOf(String text) so it never crashes, and returns an int.
- When
textis a whole number, return it as anint. - When
Integer.parseIntthrows an exception, return0. That includes an empty quantity,"", and one that isn't whole, such as"2.5".
Practiced live on the lesson page: write the Java right there and check it.