When a condition causes an exception to be thrown, that exception is thrown either by the Java virtual machine or by the Java throw statement. Exceptions are represented by objects instantiated from the class java.lang. Throwable or one of its sub-classes. Java also allows users to define classes that can throw their own (user-defined) exception objects as needed in their design; however, this new class must extend the throwable class or one of its sub-classes.
Throwable class hierarchy
Figure shows a class hierarchy diagram that illustrates some of the exception handling classes and the relationships between them. The Throwable class is a super-class in the exception hierarchy. There are two sub-classes of Throwable class: Error and Exception. The difference between the two is that the Error class deals with exceptional events from which it is generally not possible to recover, whereas the Exception class deals mostly with events from which it is possible to recover.
An exception of the Error type is non-recoverable and should not be caught. Applications should not try to catch the objects of Error class. They usually cause the Java virtual machine.
To display a message and then exit. These type of exceptions indicate a serious problem in the application and causes abnormal termination without handling. An example of a non-recoverable error is out of memory. These errors are operating system and hardware-dependent and hence cannot be handled by programmers.
An exception of the Exception type indicates an abnormal condition that must be properly handled to prevent program termination. An example of this type of error is divide by zero.
The Java Exception class is represented as follows:
Public class Exception extends Throwable { public Exception () { Super (); } public Exception (String s) { Super (s); } }
There are several sub-classes of the Error class and the Exception class. Many of these sub-classes themselves have numerous sub-classes. For instance, the class ArithmeticException is a sub-class of RuntimeException which is again a sub-class of Exception. Similarly, VirtualMachineError is a sub-class of Error which indicates that the JVMis broken or has run out of resources necessary for it to continue operating. Figure shows the inheritance hierarchy between a few classes that are meant for throwing exceptions. Classes in Java are organized in the form of groups, and each group forms a sub-tree of the inheritance tree.
Note that the Throwable class is the super-class in the inheritance hierarchy. The classes
Throwable, Error and Exception are found in the java.lang package. Some exception classes such as IOException and FileNotFoundException are defined in packages such as java.io.