Exception Handling in Java Part-III

In this lesson we will continue our discussion on exception handling inJava programming langauge.

During program execution, the Java runtime system stores the class name of every object. getClass() can be used to get an object that stores the class name. It has a getName() method. The name of the class of the actual parameter of the throw statement can be retrieved in the handler as shown below.

anyException.getClass().getName();

In the case of a user defined exception, the thrown object could include any number of data fields that might be useful in the handler.

throws Clause
The throws clause is overloaded in C++ and conveys two different meanings: one asspecification and the other as command. Java is similar in syntax but different in semantics. The appearance of an exception class name in the throws clause of Java method specifies that the exception class or any of its descendents can be thrown by the method.

A C++ program unit that does not include a throws clause can throw any exceptions. A Java method that does not include a throws clause cannot throw any checked exception, it does not handle. A method cannot declare more exceptions in its throws clause than the methods it overrides, though it may declare fewer. A method that does not throw a particular exception, but calls another method that could throw the exception, must list the exception in its throws clause.

The finally clause
A Java exception handler may have a finally clause too. A finally clause always executes when its try block executes (whether or not there is an exception). The use of try, catch and finally is presented below:
try {
}
catch () {

}
finally {
}
A finally clause is usually included to make sure that some clean-up (e.g. closing opened files) is done.