+ 2

Can someone please explain to me why the following piece of code has compilaton error?

public class Test { public static void main(String[] args) { int x = 10; int y = 2; try { for (int z = 2; z >= 0; z--) { int ans = x / z; System.out.print(ans+ " "); } } catch (Exception e1) { System.out.println("E1"); } catch (ArithmeticException e1) { System.out.println("E2"); } } }

3rd Apr 2018, 3:23 PM
Ari Ari
Ari Ari - avatar
8 Antworten
+ 14
hahaha 😅 @Jakob //I'll super active later ... will not leave any code one
3rd Apr 2018, 3:34 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 13
//Jacob fast boy 👍 place the catch block for ArithmeticException before than that one //@justin , for experimenting example of try-catch ...
3rd Apr 2018, 3:32 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
@Justin He is doing that intentionally to test the try-catch blocks.
3rd Apr 2018, 3:31 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
Try this: public class Test { public static void main(String[] args) { int x = 10; int y = 2; try { for (int z = 2; z >= 0; z--) { int ans = x / z; System.out.print(ans+ " "); } } catch (ArithmeticException e1) { System.out.println("E2"); } catch (Exception e1) { System.out.println("E1"); } } } :::: OUTPUT :::: 5 10 E2 ^Just move your default catch exception to the bottom.
3rd Apr 2018, 3:31 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
@Gaurav lol I knew you're lurking around this morning, so I have to be quick. :D
3rd Apr 2018, 3:33 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 1
One issue I see is in your for loop. You are letting z = 0 then trying to divide x by z. You cannot divide by 0 :)
3rd Apr 2018, 3:30 PM
Justin Hinkle
Justin Hinkle - avatar
+ 1
Hello thank you for the quick response. I am quite new. Can you please give more explanation as to why the default catch exception was triggered first? Thanks.
3rd Apr 2018, 3:39 PM
Ari Ari
Ari Ari - avatar
+ 1
It is processed sequentially. If the first catch is generic, any exception will be handled by this catch. Since it is considered handled, then no others need evaluated and the behavior that you really wanted doesn’t happen. Always put the generic catch as the last catch, when you define more than one catch.
4th Apr 2018, 9:33 AM
SQrL
SQrL - avatar