+ 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"); } } }
8 Respostas
+ 14
hahaha 😅 @Jakob
//I'll super active later ... will not leave any code one
+ 13
//Jacob fast boy 👍
place the catch block for ArithmeticException before than that one
//@justin , for experimenting example of try-catch ...
+ 5
@Justin
He is doing that intentionally to test the try-catch blocks.
+ 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.
+ 3
@Gaurav
lol I knew you're lurking around this morning, so I have to be quick. :D
+ 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 :)
+ 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.
+ 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.