Exception Handlers

What do you do when an error occurs in a program? In many languages, error conditions are signaled by unusual return values like 1. Programmers often don't check for exceptional values because they may assume that errors "can't happen." On the other hand, adding error detection and recovery to what should be a straightforward flow of logic can complicate that logic to the point where the normal flow is completely obscured. An ostensibly simple task such as reading a file into memory might require about seven lines of code. Error checking and reporting expands this to 40 or more lines. Making normal operation the needle in your code haystack is undesirable.

Checked exceptions manage error handling. Checked exceptions force you to consider what to do with errors where they may occur in the code. If a checked exception is not handled, this is noticed at compile time, not at run time when problems have been compounded because of the unchecked error.

A method that detects an unusual error condition throws an exception. Exceptions can be caught by code farther back on the calling stackthis invoking code can handle the exception as needed and then continue executing. Uncaught exceptions result in the termination of the thread of execution, but before it terminates the thread's UncaughtExceptionHandler is given the opportunity to respond to the exception as best it canperhaps doing nothing more than reporting that the exception occurred.

An exception is an object, with type, methods, and data. Representing exceptions as objects is useful, because an exception object can include data, methods, or both to report on or recover from specific kinds of exceptions. Exception objects are generally derived from the Exception class, which provides a string field to describe the error. All exceptions must be subclasses of the class Throwable, which is the superclass of Exception.

The paradigm for using exceptions is the trycatchfinally sequence: you try something; if that something throws an exception, you catch the exception; and finally you clean up from either the normal code path or the exception code path, whichever actually happened.

Here is a getdataSet method that returns a set of data read from a file. If the file for the data set cannot be found or if any other I/O exception occurs, this method throws an exception describing the error. First, we define a new exception type BadDataSetException to describe such an error. Then we declare that the method getdataSet tHRows that exception using a throws clause in the method header:

class BadDataSetException extends Exception { }

class MyUtilities {
public double[] getDataSet(String setName)
throws BadDataSetException
{
String file = setName + ".dset";
FileInputStream in = null;
try {
in = new FileInputStream(file);
return readDataSet(in);
} catch (IOException e) {
throw new BadDataSetException();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
; // ignore: we either read the data OK
// or we're throwing BadDataSetException
}
}
}
// ... definition of readDataSet ...
}



First we turn the data set name into a file name. Then we try to open the file and read the data using the method readDataSet. If all goes well, readDataSet will return an array of doubles, which we will return to the invoking code. If opening or reading the file causes an I/O exception, the catch clause is executed. The catch clause creates a new BadDataSetException object and throws it, in effect translating the I/O exception into an exception specific to getdataSet. Methods that invoke geTDataSet can catch the new exception and react to it appropriately. In either casereturning successfully with the data set or catching and then throwing an exceptionthe code in the finally clause is executed to close the file if it was opened successfully. If an exception occurs during close, we catch it but ignore itthe semicolon by itself forms an empty statement, which does nothing. Ignoring exceptions is not a good idea in general, but in this case it occurs either after the data set is successfully readin which case the method has fulfilled its contractor the method is already in the process of throwing an exception. If a problem with the file persists, it will be reported as an exception the next time we try to use it and can be more appropriately dealt with at that time.

You will use finally clauses for cleanup code that must always be executed. You can even have a try-finally statement with no catch clauses to ensure that cleanup code will be executed even if uncaught exceptions are thrown.

If a method's execution can result in checked exceptions being thrown, it must declare the types of these exceptions in a throws clause, as shown for the getdataSet method. A method can throw only those checked exceptions it declaresthis is why they are called checked exceptions. It may throw those exceptions directly with tHRow or indirectly by invoking a method that throws exceptions. Exceptions of type RuntimeException, Error, or subclasses of these exception types are unchecked exceptions and can be thrown anywhere, without being declared.

Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some waysuch as the IOException that may occur reading a file. Declaring the checked exceptions that a method throws allows the compiler to ensure that the method throws only those checked exceptions it declared and no others. This check prevents errors in cases in which your method should handle another method's exceptions but does not. In addition, the method that invokes your method is assured that your method will not result in unexpected checked exceptions.

Unchecked exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time. For example, the ArrayIndexOutOfBoundsException thrown when you access outside the bounds of an array tells you that your program calculated an index incorrectly, or failed to verify a value to be used as an index. These are errors that should be corrected in the program code. Given that you can make errors writing any statement it would be totally impractical to have to declare or catch all the exceptions that could arise from those errorshence they are unchecked.

We Are Founder..