Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception

 
siddharth das
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt on following program.

package chapters.chap02;
public class Ques04 {
public static void main(String[] args) {
System.out.println(test1());
}
static int test1(){
if (test2() == -1)
{
try{
throw new Exception("test1");
}catch(Exception e){
return 5;
}finally{
return 3;
}
}else{
return 6;
}
}
static int test2(){
if (true){
try{
throw new Exception("test2");
}finally{
return -1;
}
}else{
return 9;
}
}
}

In test2(),an exception is thrown.But where it is handled?The program compiles And run successfully and produce output as 3.
Please suggest me.
Thanks in advance.
 
Rob Spoor
Sheriff
Posts: 20822
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It kind of surprises me a bit that it compiles, but after a bit of testing I found out why.

A finally block will always get executed*. Therefore, the "return -1" will overrule the exception that is thrown. Remove that return statement and the compiler complains that Exception must be caught or thrown.


* provided there is no System.exit, JVM crash or other unrecoverable error such as the PC dying.
 
when your children are suffering from your punishment, tell your them it will help them write good poetry when they are older. Like this tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!