Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when an exception is thrown?

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();
    }
}
like image 937
rni902 Avatar asked Oct 26 '15 17:10

rni902


1 Answers

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.

like image 183
Makoto Avatar answered Sep 23 '22 21:09

Makoto