What’s the result of running the following code? |
|
|
The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. The general syntax looks like:
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. 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 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". |

