Exception Handling in Java 1

Exception handling in Java is based on C++ but is designed to be more in line with OOP. It includes a collection of predefined exceptions that are implicitly raised by the JVM. All java exceptions are objects of classes that are descendents of Throw able class. There are two predefined subclasses of Throw able: Error and Exception.

Error and its descendents are related to errors thrown by JVM, e.g. out of heap memory. Such an exception is never thrown by the user programs and should not be handled by the user.

User programs can define their own exception classes. Convention in Java is that such class’s subclass the Exception class. There are two predefined descendents of Exception class: IOException and Runtime Exception. IOException deals with errors in I/O operations. In the case of RuntimeException there are some predefined exceptions which are, in many cases, thrown by JVM for errors such as out of boundsexception, and Null pointer exception.

Checked and Unchecked Exceptions
Exceptions of class Error and RuntimeException are called unchecked exceptions. They are never a concern of the compiler. A program can catch unchecked exceptions but it is not required. All others are checked exceptions. Compiler ensures that all the checked exceptions a method can throw are either listed in its throws clause or are handled inside the method.

 Exception Handling in Java 2

We will continue our discussion on Exception handling in this lesson. In this lesson we will learn to codeException handlers.

Exception Handler
Exception handler in Java is similar to C++ except that the parameter of every catch must be present and its class must be descendent of Throwable. The syntax of try is exactly same as C++ except that there is an optional finally clause as well.

Consider the following example:
class MyException extends Exception {
   public MyException() { }
   public MyException(String message) {
      super (message);
   }
}
This exception can be thrown with
throw new MyException();

Or

MyException myExceptionObject = new MyException();
throw myExceptionObject;

Binding of exception is also similar to C++. If an exception is thrown in the compound statement of try construct, it is bound to the first handler (catch function) immediately following the try clause whose parameter is the same class as the thrown object or an ancestor of it. Exceptions can be handled and then re-thrown by including a throw statement without an operand at the end of the handler. To ensure that exceptions that can be thrown in a try clause are always handled in a method, a special handler can be written that matches all exceptions. For example:

catch (Exception anyException) {
}