| Mobile | RSS

Java Tutorial : Exception Classes 

11th Oct, 2009 | No Comment | Posted in Java by Alex Jose

Exception Handling

To handle exceptions, the Java run-time system searches for an exception-handler. In Java, a catch statement is an exception-handler that is used to handle an exception. The search for an exception-handler begins with the method in which the exception is raised. If no appropriate exception-handler is found, the Java run-time system searches the exception-handler in the next higher method hierarchy. The type of exception handled by the exception-handler should match the type of exception thrown. The Java run-time system proceeds with the normal execution of the program after an exception gets handled. If no appropriate exception-handler is found by the Java run-time system, the program is terminated.

In Java, the Throwable class is the superclass of all the exception classes. Object class is the base class of the exception hierarchy. The Exception class and the Error class are two subclasses of the Throwable class.

Exception Hierarchy

Exception Hierarchy

Throwable Class

The Throwable class is a subclass of the Object class. The Throwable class is the superclass of all the exception objects that are thrown in Java. You can throw only those exception objects that are derived from the Throwable class. The following syntax shows how to declare a constructor for the Throwable class:

Throwable()

In the preceding syntax, a new Throwable constructor with no arguments is created.

You can also declare a constructor for the Throwable class with a user-defined message. The following syntax shows how to declare a constructor of the Throwable class with a user-defined message:

Throwable(String message)

In the preceding syntax, message represents the specified message included in the Throwable class.

Exception Class

The Exception class has various subclasses, such as ClassNotFoundException, IllegalAccessException, and RuntimeException. The ClassNotFoundException exception is thrown when a class is being referred, but no definition for the class with the specified name is found. The IllegalAccessException exception is thrown when a particular method is not found. The RuntimeException exception handles the exceptions that are raised in the programs during run time.

Error Class

The Error class defines exceptions related to the Java run-time environment. For example, OutOfMemoryError is an error that occurs when there is insufficient system memory to execute a program. A program is abruptly aborted when an Error object is thrown. The Error class consists of two types of constructors, one without any error message and the other with an error message. The following syntax shows the constructor of the Error class with no message:

Error()

The following syntax shows the constructor of the Error class having information about the error:

Error(String message)

Related Posts with Thumbnails