What’s the result of running the following code? Is an exception thrown? If so, which exception is thrown?
Here is the code in question:
As you can see in the comments above, the variable i becomes equal to 2 and the variable j becomes equal to 0. This means that in the "if(i/j > 1)" statement that follows, 2 will be divided by 0.
Of course, dividing by 0 is not allowed and should throw an exception under normal circumstances, but the question is whether an exception will still be thrown even though the division being done here is inside an if statement.
ArithmeticException is thrown by the code above
And the answer is yes – an exception will still be thrown. The exception that gets thrown when a division by 0 is done is the ArithmeticException. So, the first thing that gets printed out is "arithmetic error".
The next question is whether the finally block actually executes. If you read this question: Java Finally Block – then you would know the answer. But, in case you haven’t read that – the answer is yes, the finally block will execute in this code.
This means that the output after running this code will be: "arithmetic error In the finally block".
It’s worth noting that if we didn’t have the "catch(ArithmeticException e)" block in the code above, then the exception would have just been caught by the "catch(Exception e)" block and the output would have been "generic exception. In the finally block".