Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
siddharth das
Ranch Hand
Posts: 133
  • 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
Pie
Posts: 20511
54
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic