Java Reference
In-Depth Information
We could have simply ignored the exceptions in the divide() method. This might not be a bad
approach in this particular situation, but the first problem the calling program would have is
determining the source of the exception. After all, such exceptions might also arise in the calling
program itself. A second consideration could arise if the divide() method was more complicated.
There could be several places where such exceptions might be thrown, and the calling method would
have a hard time distinguishing them.
An Example of an Exception Class
Another possibility is to catch the exceptions in the method where they originate, then pass them on to
the calling program. You can pass them on by throwing new exceptions that provide more granularity
in identifying the problem (by having more than one exception type, or by providing additional data
within the new exception type). For example, you could define more than one exception class of your
own that represented an ArithmeticException , where each reflected the specifics of a particular
situation. This situation is illustrated here.
void (...) {
try
method1
{
method
call
{
int (...) throws ,
method2 Exception1 Exception2
int x = (...);
method2
{
two varieties
of the exception
are
distinguished
new exception
thrown
try
{
catch( e ) {
//Handle exception
Exception1
{
//try block code that may
//throw ArithmeticException
exception
thrown
}
catch(
}
catch( ArithmeticException e )
{
Exception2
{
e ) {
//Analysis code...
if(...)
throw ;
else
throw ;
//Handle exception
}
Exception1
Exception2
}
}
}
This shows how two different circumstances causing an ArithmeticException in method2() , are
differentiated in the calling method, method1() . The method, method2() , can either throw an
exception of type Exception1 , or of type Exception2 , depending on the analysis that is made in the
catch block for the ArithmeticException type. The calling method has a separate catch block
for each of the exceptions that may be thrown.
You could also define a new exception class that had instance variables to identify the problem more
precisely. Let's suppose that in the last example, we wanted to provide more information to the calling
program about the error that caused each exception in the divide() method. The primary exception
can be either an ArithmeticException or an ArrayIndexOutOfBoundsException , but since
we're dealing with a specific context for these errors we could give the calling program more
information by throwing our own exceptions.
Let's take the ArithmeticException case as a model and define our own exception class to use in
the program to help identify the reason for the error more precisely.
Search WWH ::




Custom Search