I am having issues understanding what happens when an exception gets thrown.
What happens to the exception that is thrown? What handles it to ensure that the program does not crash?
For instance, in this example from this tutorial, what will deal with the ArithmeticException
that is thrown?
static int remainder(int dividend, int divisor)
throws DivideByZeroException {
try {
return dividend % divisor;
}
catch (ArithmeticException e) {
throw new DivideByZeroException();
}
}
The tutorial you link to emphasizes an important difference in what types of exceptions there are in Java, namely, whether an exception is checked or unchecked.
A checked exception is one that requires you as the developer to either catch it (i.e. deal with it), or declare it to be thrown and dealt with upstream. The expectation is that you can recover from these sorts of exceptions.
An unchecked exception is one that may or may not crop up during the natural execution of the application, and may not introduce a natural way for the application to recover. Catching them is often frowned upon since it is often indicative of poor design (you allowed a zero to make its way to a division operation, that's an illegal argument!).
In this scenario, because the method remainder
declares that it is throwing a DivideByZeroException
, all upstream callers of it must handle its exception either by:
public static void main(String[] args) {
try {
NitPickyMath.remainder(1, 0);
} catch (DivideByZeroException e) {
e.printStackTrace();
}
}
...or by:
public static void main(String[] args) throws DivideByZeroException {
NitPickyMath.remainder(1, 0);
}
The caveat to the latter form is that nothing will deal with the exception, and it will cause the application to crash.
...what will deal with the
ArithmeticException
that is thrown?
You already are dealing with it by placing it in a catch
block. You're simply re-throwing a checked exception to deal with the actual error resulting from dividing 1 into 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With