While playing with exception handling in Java I noticed that no exception is thrown when some illegal runtime operation is being done in the catch block in Java.
Is that a bug in the language or am I missing something ? Could someone please look into it - as in why no exception is thrown from the catch block.
public class DivideDemo {
@SuppressWarnings("finally")
public static int divide(int a, int b){
try{
a = a/b;
}
catch(ArithmeticException e){
System.out.println("Recomputing value");
/* excepting an exception in the code below*/
b=0;
a = a/b;
System.out.println(a);
}
finally{
System.out.println("hi");
return a;
}
}
public static void main(String[] args) {
System.out.println("Dividing two nos");
System.out.println(divide(100,0));
}
}
Is that a bug in the language or am I missing something ?
It's because you have return
statement in your finally
block:
finally {
System.out.println("hi");
return a;
}
This return
statement effectively swallows exception and "overrides it" with returned value.