Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
finally clauses -- that's next month's topic. Subsequent articles will discuss other members of the bytecode family. NitPickyMath that provides methods that perform addition, subtraction, multiplication, division, and remainder on integers. NitPickyMath performs these mathematical operations the same as the normal operations offered by Java's "+", "-", "*", "/", and "%" operators,
except the methods in NitPickyMath throw checked exceptions on overflow, underflow, and divide-by-zero conditions. The Java virtual machine will throw an ArithmeticException on an integer divide-by-zero, but will not throw any exceptions on overflow and underflow. The exceptions thrown by the methods
of NitPickyMath are defined as follows:class OverflowException extends Exception {
}
class UnderflowException extends Exception {
}
class DivideByZeroException extends Exception {
}
A simple method that catches and throws exceptions is the remainder method of class NitPickyMath:
static int remainder(int dividend, int divisor)
throws DivideByZeroException {
try {
return dividend % divisor;
}
catch (ArithmeticException e) {
throw new DivideByZeroException();
}
}
The remainder method simply performs the remainder operation upon the two ints passed as arguments. The remainder operation throws an ArithmeticException if the divisor of the remainder operation is a zero. This method catches this ArithmeticException and throws a DivideByZeroException.
The difference between a DivideByZero and an ArithmeticException exception is that the DivideByZeroException is a checked exception and the ArithmeticException is unchecked. Because the ArithmeticException is unchecked, a method need not declare this exception in a throws clause even though it might throw it. Any exceptions that
are subclasses of either Error or RuntimeException are unchecked. (ArithmeticException is a subclass of RuntimeException.) By catching ArithmeticException and then throwing DivideByZeroException, the remainder method forces its clients to deal with the possibility of a divide-by-zero exception, either by catching it or declaring
DivideByZeroException in their own throws clauses. This is because checked exceptions, such as DivideByZeroException, thrown within a method must be either caught by the method or declared in the method's throws clause. Unchecked exceptions,
such as ArithmeticException, need not be caught or declared in the throws clause.