Chapter 3.7.3- Exceptions in TextIO | Introduction to Programming Using Java
3.7.3 Exceptions in TextIO
When TextIO reads a numeric value from the user, it makes sure that the user’s response is legal, using a technique similar to the while loop and try..catch in the previous example. However, TextIO can read data from other sources besides the user. (See Subsection 2.4.5.)
When it is reading from a file, there is no reasonable way for TextIO to recover from an illegal value in the input, so it responds by throwing an exception. To keep things simple, TextIO only throws exceptions of type IllegalArgumentException, no matter what type of error it encounters.
For example, an exception will occur if an attempt is made to read from a file after all the data in the file has already been read. In TextIO, the exception is of type IllegalArgumentException. If you have a better response to file errors than to let the program crash, you can use a try..catch to catch exceptions of type IllegalArgumentException.
For example, suppose that a file contains nothing but real numbers, and we want a program that will read the numbers and find their sum and their average. Since it is unknown how many numbers are in the file, there is the question of when to stop reading.
One approach is simply to try to keep reading indefinitely. When the end of the file is reached, an exception occurs. This exception is not really an error—it’s just a way of detecting the end of the data, so we can catch the exception and finish up the program.
We can read the data in a while (true) loop and break out of the loop when an exception occurs. This is an example of the somewhat unusual technique of using an exception as part of the expected flow of control in a program.
To read from the file, we need to know the file’s name. To make the program more general, we can let the user enter the file name, instead of hard-coding a fixed file name in the program. However, it is possible that the user will enter the name of a file that does not exist.
When we use TextIO.readfile to open a file that does not exist, an exception of type IllegalArgumentException occurs. We can catch this exception and ask the user to enter a different file name. Here is a complete program that uses all these ideas:
Read More…
Introduction to Programming Using Java – David J. Eck
Chapter 2 – Names and Things | Introduction to Programming Using Java
Chapter 2.5.1 – Arithmetic Operators | Introduction to Programming Using Java
Chapter 3.6.4 – Definite Assignment | Introduction to Programming Using Java
Chapter 3.7.2- try..catch | Introduction to Programming Using Java
1 thought on “Chapter 3.7.3- Exceptions in TextIO | Introduction to Programming Using Java”