Runtime Exceptions in java

Java has a requirement that any exception, other than RuntimeException or Error, must be either caught by the method or specified in the throws clause of the method. Since a runtime exception, as the name suggests, is usually thrown by the runtime system, it may not be practicable for application code to try to catch all such exceptions. For this reason, the requirement to throw or catch runtime exceptions is relaxed by the Java compiler. For example, if instead of an integer, we supply a real number as an argument to the MultiplyClass application, the runtime NumberFormatException will be thrown. However, there is no requirement to either catch or specify this exception.

This suggests the possibility of subclassing your own exceptions as runtime exceptions. We can rewrite the ArgumentTooBigException class as a subclass of RuntimeException.

ArgumentTooBigException

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

We will now rewrite all the methods of the MultiplyClass application without having to either catch or specify the ArgumentTooBigException.


MultiplyClass

public class MultiplyClass
{

public static void main(String[] args)
{
String resultString;


int arg1;
int arg2;
int result;

arg1=Iteger.parseInt(args[0]);
arg2=Integer.parseint(args[1]);


result = multiplyHandler (arg1, arg2);
resultString = Integer.toString(result);
System.out.println(''The product of " + args[0]
+ " and " + args[1] + " is " + resultString);
}

static int multiplyHandler(int arg1, int arg2)
{
return multiply(arg1, arg2);
}

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

However, this use of runtime exceptions is not good software engineering practice. In the multiply method, we have decided to throw the ArgumentTooBigException. We have also made the decision not to catch this exception in the multiply method. So the decision whether or not to catch the exception is made by the invoking method, multiplyHandler. The only way the developer of the multiplyHandler method knows which exceptions he or she may need to catch is by examining the code of multiply to see what exceptions are thrown. On a large project, multiplyHandler and multiply may be developed by separate teams. The multiply method may be part of a general utilities class, which may be invoked by a large number of different methods.In all the preceding scenarios, we would not want users of the multiply method to have
to trawl through our code. All this violates the principle of information hiding; namely, the invoker of any method needs only to be aware of the method interface but not details of the invoked method body. Consequently, it is good practice to create your own exceptions as subclasses of the Exception class. In this way, the catch or specify exceptions requirement is enforced.

No comments:

Post a Comment