Java Reference
In-Depth Information
When this happens, the statements, if any, in the catch block are executed. Java lets us put any statements in a
catch block. In this case, we print the contents of the exception object, e , and a message, and the program exits. When
run, with no file input.txt , this code prints the following:
java.io.FileNotFoundException: input.txt
Correct the problem and try again
The program does not have to exit. If the exit statement were omitted, the program would simply continue with
the statement, if any, after the catch block. If we want, we could also call another method to continue execution.
To continue the example, consider the following:
try {
Scanner in = new Scanner(new FileReader("input.txt"));
n = in.nextInt();
}
We attempt to read the next integer from the file. Now, many things can go wrong: the file may not exist, the
next item in the file may not be a valid integer, or there may be no “next” item in the file. These will throw “file not
found,” “input mismatch,” and “no such element” exceptions, respectively. Since these are all subclasses of the class
Exception , we can catch them all with the following:
catch (Exception e) {
System.out.printf("%s\n", e);
System.out.printf("Correct the problem and try again\n");
System.exit(1);
}
When the file is empty, this code prints this:
java.util.NoSuchElementException
Correct the problem and try again
When the file contains the number 5.7 (not an integer), it prints this:
java.util.InputMismatchException
Correct the problem and try again
If necessary, Java allows us to catch each exception separately. We can have as many catch constructs as needed.
In this example, we could write the following:
try {
Scanner in = new Scanner(new FileReader("input.txt"));
n = in.nextInt();
}
catch (FileNotFoundException e) {
//code for file not found
}
catch (InputMismatchException e) {
//code for “invalid integer” found
}
catch (NoSuchElementException e) {
//code for “end of file” being reached
}
Search WWH ::




Custom Search