J.E.D.I.
class ThrowsDemo { public static void mainString args[] {
try { ThrowingClass.myMethod;
} catch ClassNotFoundException e { System.out.printlne;
} }
}
The program gives the following output: java.lang.ClassNotFoundException: just a demo
2.5 Exception Categories
2.5.1 Exception Classes and Hierarchy
As mentioned earlier, the root class of all exception classes is the Throwable class. Presented below is the exception class hierarchy. These exceptions are
all defined in the java.lang package.
Exception Class Hierarchy Throwable
Error LinkageError, ...
VirtualMachineError, ... Exception
ClassNotFoundException, CloneNotSupportedException,
IllegalAccessException, InstantiationException,
InterruptedException, IOException,
EOFException, FileNotFoundException,
... RuntimeException,
ArithmeticException, ArrayStoreException,
ClassCastException, IllegalArgumentException,
IllegalThreadStateException and NumberFormatException as
subclasses IllegalMonitorStateException,
IndexOutOfBoundsException, NegativeArraySizeException,
NullPointerException, SecurityException
...
Table 2: Exception Class Hierarchy
Now that you’re quite familiar with several exception classes, it is time to introduce to this rule: Multiple catches should be ordered from subclass to superclass.
class MultipleCatchError {
Introduction to Programming II Page 31
J.E.D.I.
public static void mainString args[]{ try {
int a = Integer.parseIntargs [0]; int b = Integer.parseIntargs [1];
System.out.printlnab; } catch Exception e {
System.out.printlne; } catch ArrayIndexOutOfBoundsException e2 {
System.out.printlne2; }
System.out.printlnAfter try-catch-catch.; }
}
Compiling the code would produce this error message since the Exception class is a superclass of the ArrayIndexOutOfBoundsException class.
MultipleCatchError.java:9: exception java.lang.ArrayIndexOutOfBoundsException has already been caught
} catch ArrayIndexOutOfBoundsException e2 {
2.5.2 Checked and Unchecked Exceptions
An exception is either checked or unchecked. A checked exceptions is just an exception that is checked by Java compiler. The compiler
makes sure that the program either catches or lists the occurring exception in the throws clause. If the checked exception is neither caught nor listed, then a compiler error will
occur.
Unlike checked exceptions, unchecked exceptions are not subject to compile-time checking for exception handling. The built-in unchecked exception classes are Error,
RuntimeException, and their subclasses. Thus, these type of exceptions are no longer checked because handling all such exceptions may make the program cluttered and may
most likely become a nuisance.
2.5.3 User-Defined Exceptions