wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

siddharth das
Ranch Hand

Joined: Aug 17, 2007
Posts: 124
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

Joined: Oct 27, 2005
Posts: 19654
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception
 
Similar Threads
try finally without a catch:
Exception
somebody pls explain why this code does not give an exception
exception doubt
Exception