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:

public static void main(String[ ] args) {

int i=1;
int j=1;

try
{
	i++; //becomes 2
	j--; //becomes 0
	
	if (i/j > 1)
	{
		i++;
	}
}

catch(ArithmeticException e)
{				
	System.out.println("arithmetic error.");
}

catch(ArrayIndexOutOfBoundsException e)
{

	System.out.println("Array index out of bounds");
}

catch(Exception e)
{		
	System.out.println("generic exception.");
}

finally
{

	System.out.println("In the finally block");
	
}
}

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".

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.