Why use Custom Exception Classes in Java
Quite frequently, we read in Java books that we can inherit from Exception/RuntimeExcetion classes or implement the Throwable interface in order to create application specific exception classes.
There are scenarios where the exception hierarchy present in the Java JDK is not sufficient to capture the essence of the erroneous condition in an application. These custom exceptions can be thrown using the throw keyword whenever the corresponding condition occurs.
The exception handler catch blocks can be present in the same method or can be present in the caller code.
But most of the applications don't not have custom exceptions unless a lot of thinking has been done over the design of the application. This is probably because of the time constraints in a project or the lack of knowledge.
Anyways, here is an example from my experience where we used custom exceptions. The application had a JSP page where we will forward the user to in case of any irrecoverable exception. The need of custom exception was to show more meaningful message to the user. A user does not know what is a NullPointerException or ArrayIndexOutofBoundsException. What he understands is any fallacy in the application with regard to the functional aspects of the application.
We have a sample custom exception scenario with various classes in this example being:
ValueTooLarge : Exception to be thrown when the result of a business calculation is not permissible.
BaseException : Provides logging of exceptions so that not every class has to log the exception
CoolingEfficiencyCalculator : Calculates the efficiency of a fridge and raises the exception if the value of efficiency is greater than 999
RequestProcessor: Receives the request from the user with all the values of the form and calls the calculate method and handles the ValueTooLarge exception to display the message corresponding to the code Error123 as read from the config file.
public class ValueTooLarge extends BaseException {
public ValueTooLarge() {
super();
}
public ValueTooLarge(String msg) {
super(msg)
}
}
==================================================public class BaseException extends Exception{
public BaseException() {
super();
// Log this exception in the
error log
LogUtil.writeException(LogUtil.OTHER_ERROR, this);
}
public BaseException(String msg) {
super(msg);
// Log this exception in the
error log
LogUtil.writeException(LogUtil.OTHER_ERROR,
this);
}
} ===================================================//This class is the point where value too large exception will be raised
public class CoolingEfficiencyCalculator {
public int calculate( int weight, int temperature) throws ValueTooLarge{
int efficiency = (weight/temperature)*100;
throw new ValueTooLarge();
}
}
==================================================public class RequestProcessor {
public void processRequest {
CoolingEfficiencyCalculator
coolingEfficiencyCalculator = new CoolingEfficiencyCalculator();
try{
coolingEfficiencyCalculator.calculate(Record serviceRecord);
} catch (ValueTooLarge vtle) {
addException("Error123");
}
}
}
So next time someone asks you about custom exception just use this example and you are done :)
Hi Sandeep , you bring a good topic , while creating custom exception may I ask how do you decide whether to go for checked exception or unchecked exception ?
ReplyDeleteThanks
Javin
5 difference between iterator and enumeration
The same rule that we use for JDK default checked and unchecked exceptions applies for custom exception.
ReplyDeleteI have made the ValueTooLarge exception as checked because the developer doesn't know whether the value of efficiency will increase 999 or not. It depends upon the input entered by the user and hence a checked exception.
On the other hand, an exception to indicate the non existence of a bean in the memory could be because the application didn't initialize one and hence a candidate for unchecked custom exception.
You should first look for exception classes in the JDK or the various validation projects that have the same semantic meaning as the exception you really want to throw.For example, you can reuse IndexOutOfBoundsException, or subclass it. The runtime exceptions NullPointerException and IllegalArgumentException can also be used. However, if you have any useful context for the programmer, you can provide it. The ValueToLarge class should have only one constructor and a couple of (unshown) getters:
ReplyDeletepublic ValueTooLarge(int value, int bound) {
this("The value, " + value + " exceeded the bound " + bound + ".");
this.value = value;
this.bound = bound;
}
It keeps programmers from coming up with new and different messages every time the use the exception class.
Unless you have an absolutely good reason for deriving from Exception, RuntimeException should be used instead.
ReplyDeletenice information on custom classes in java
ReplyDelete