Java Reference
In-Depth Information
The Order of catch Clauses
catch clauses are checked in the order they appear. If an exception is caught in
a catch clause, any subsequent catch blocks are ignored. Watch for invalid try-catch
statements that contain unreachable code and therefore do not compile. For example, do
you see what is wrong with the following try-catch statement?
5. try {
6. FileReader fis = new FileReader(fileName);
7. System.out.println(fileName + “ was found”);
8. char data = (char) fis.read();
9. System.out.println(“Just read: “ + data);
10. } catch(IOException e) {
11. System.out.println(“Something went wrong”);
12. e.printStackTrace();
13. } catch(FileNotFoundException e) {
14. System.out.println(“Oops - file not found: “ +
15. e.getMessage());
16. }
FileNotFoundException is a child class of IOException . If a FileNotFoundException is
thrown within this try block, it will be caught on line 10. Therefore, it is not possible for
the catch block on line 13 to ever execute. This code does not compile and generates the
following compiler error:
MyFileReader.java:13: exception java.io.FileNotFoundException has
already been caught
} catch(FileNotFoundException e) {
^
A catch clause of a try statement cannot catch an exception that is a child class of an
earlier catch clause.
The Handle or Declare Rule
According to the exam objectives, you should know “that the exception may be a runtime
exception, a checked exception, or an error.” These different types of exceptions are
important because of the Handle or Declare Rule, which this section discusses. Exceptions
fi t into three categories:
Runtime exceptions An exception is referred to as a runtime exception if its data type is
java.lang.RuntimeException or a subclass of RuntimeException .
Search WWH ::




Custom Search