Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1348 :
Posted: Sun Jan 05, 2014 4:09 pm
by coelhorrc
Why does the following code prints 5? I thought that every exception would stop the thread.
int k = 0;
try{
int i = 5/k;
}
catch (ArithmeticException e){
System.out.println("1");
}
catch (RuntimeException e){
System.out.println("2");
return ;
}
catch (Exception e){
System.out.println("3");
}
finally{
System.out.println("4");
}
System.out.println("5");
Re: About Question enthuware.ocajp.i.v7.2.1348 :
Posted: Sun Jan 05, 2014 8:51 pm
by admin
If an exception is left uncaught, then that stops the thread. But here, we are catching the exception. You might want to check this out:
http://www.javamex.com/tutorials/except ... dler.shtml
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1348 :
Posted: Wed Dec 17, 2014 2:24 am
by Deleted User 1713
In the explanation to the question it sais: "Remember : finally is always executed even if try or catch return; (Except when there is System.exit() in try.)"
You can also have System.exit() in the catch clause. This will prevent finally from being executed as well.
Re: About Question enthuware.ocajp.i.v7.2.1348 :
Posted: Wed Dec 17, 2014 8:29 am
by admin
Yes, that is a good point.
Re: About Question enthuware.ocajp.i.v7.2.1348 :
Posted: Mon Aug 21, 2017 11:27 am
by Kevin30
If I put a return statement in the catch (AritmeticException e) clause instead of the catch (RuntimeException e) clause, then 5 will not print:
Code: Select all
public class TestClass{
public static void main(String args[]){
int k = 0;
try{
int i = 5/k;
}
catch (ArithmeticException e){
System.out.println("1");
return ;
}
catch (RuntimeException e){
System.out.println("2");
}
catch (Exception e){
System.out.println("3");
}
finally{
System.out.println("4");
}
System.out.println("5");
}
}
The printout here is:
1
4
instead of:
1
4
5
Can you tell me what the logic is with regard to the return statement?
I'm guessing that the following things will happen, in order:
- of course the ArithmeticException is being caught,
- then 1 gets printed,
- then it encounters the return statement,
- but finally always runs (except in case of an System.exit()) so 4 gets printed,
- and now what? the code returns to where?
Re: About Question enthuware.ocajp.i.v7.2.1348 :
Posted: Mon Aug 21, 2017 8:51 pm
by admin
The control returns to whoever called the method. In this case, it is the JVM that invoked the main method. So the control goes back to the JVM.