Creating Exception Classes in java

It is possible to create your own exception classes. These exceptions are then explicitly thrown in the program code using the throw statement. An exception class is created by creating a subclass of the Java-supplied Exception class. It is possible to create a subclass of a class lower in the exception class hierarchy, for example, a subclass of the RuntimeException class. However, this is not good practice, as we shall see later in this chapter.

As an example, we will create an exception class, ArgumentTooBigException, that catches exceptions thrown whenever arguments supplied to a program exceed a given value.

ArgumentTooBigException

public class ArgumentTooBigException extends Exception
{
public ArgumentTooBigException(){}
}


We can use any valid unique identifier for the exception class name. However, the exception class hierarchy in the Java language uses the standard of an exception class ending with the string Exception. It is good practice to continue with this convention, so our class has been named ArgumentTooBigException. It consists of a single constructor that does nothing other than enable the instantiation of the thrown exception object.

Suppose we have a class, MultiplyClass, that consists of single method, multiply, which returns the product of two supplied arguments. If either argument is greater than 99,
we want to throw our ArgumentTooBigException.

multiply Method

public class MultiplyClass
{

public static int multiply(int arg1, int arg2)
throws ArgumentTooBigException {
if (arg1 > 99 | arg2 > 99)
{
throw new ArgumentTooBigException();
}
return arg1 * arg2;
}
}



Note that in the statement (line 6),

throw new ArgumentTooBigException();

The new keyword creates a throwable object corresponding to the ArgumentTooBigException class. The throw keyword then throws this object. Note that the method declaration includes the clause throws ArgumentTooBigException (line 4). Java has a requirement that any exception, other than runtime exceptions, must be either caught by the method or specified in the throws clause of the method. Note that a method is not required to declare in its throws clause any subclasses of Error that might be thrown during its execution. Since the multiply method does not catch the exception,
it must be specified in the throws clause. Since the exception is part of the method declaration and so part of its interface, any method that invokes the multiply method is aware of the ArgumentTooBig exception, and the invoking method can decide whether to catch the exception.

No comments:

Post a Comment