Java Exception Classes

When an exception is thrown, an object is thrown corresponding to one of the supplied Java exception classes. In Section 6.1, we have seen an example of an exception being thrown
by the runtime system; an exception can also be explicitly thrown by the program code. This is illustrated in Section 6.3. Figure 6.1 shows the exception class hierarchy outline.

Note that the Error hierarchy describes serious internal errors that applications should not normally try to catch. A large number of exception classes, both runtime and nonruntime,
are inherited from the Exception class

A thrown exception can be caught by an exception class higher in the class hierarchy. For example, lines 18–21 from the Multiply example in the previous section,

}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(''Two integer arguments are required");
}


Figure Exception hierarchy outline.

could be replaced by

}
catch (IndexOutOfBoundsException e)
{
System.out.println(''Out of Bounds Exception");
}


Usually, it is good practice to use the most specific exception class. In the preceding example, the code in the catch statement must be able to handle any possible StringIndexOutOfBounds exceptions as well as ArrayIndexOutOfBounds exceptions.

No comments:

Post a Comment