Why this problem print 3 4? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this problem print 3 4?

public static void main(String[] args){ try{ int[] array = new int [4]; array[8] = 40/0; System.out.println(“1”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“2”); } catch(ArithmeticException e){ System.out.println(“3”); } finally{ System.out.println(“4”); } }

3rd Jun 2020, 7:53 PM
Juan Debenedetti
Juan Debenedetti - avatar
2 Answers
+ 4
You try to do 40/0 which isn't allowed, so it doesn't print 1. It fails because it's not allowed by the rules of arithmetic, so it prints 3 and not 2. Then it finally prints 4. EDIT: If you're expecting an out of bounds error, the reason you're not getting one is because it fails before it can assign 40/0 to the array.
3rd Jun 2020, 7:55 PM
Ben Allen (Njinx)
Ben Allen (Njinx) - avatar
+ 1
you are try 40/0 it causes ArithmeticException but it is catched and prints 3 instead, then code continue after catch in finally block and prints 4 after finally there are no other code so its ends
4th Jun 2020, 6:11 AM
zemiak