my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

arivu mathi
Ranch Hand

Joined: Jun 26, 2006
Posts: 38
public class Test2{
public static void main(String args[]){
System.out.println(method());
}
public static int method(){
try{
throw new Exception();
return 1;
}
catch(Exception e){
return 2;
}
finally{
return 3;
}
}
}

i'm getting unreachable statement as compiler error....
can u explain ....
K Sujit
Ranch Hand

Joined: Mar 23, 2005
Posts: 33
May be because of the return 1; statement, I hope you won't get the compiler error if you remove that.

And then if you run it may return you 2. I don't understand how return 3; is going to behave.

Hope somebody will execute it and tell.


I wish java run in my veins.
Dinesh Bang
Ranch Hand

Joined: Jun 15, 2006
Posts: 52
Here in the above code :
the statement "return 1;" is unreachable as it comes after the explicit throw exception statement. Thus the statements written after the throw in the try block are all unreachable codes, as they will never be executed.
In this code statements ,
the finally block doesn't work normally as even after the return from catch block, the finally block has to run and return value.
Thus we get o/p 3.


SCJP 1.4,SCBCD 1.3, SCWCD 1.5, ???
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
More About the Finally Clause
 
wood burning stoves
 
subject: Exception
 
Similar Threads
try and catch
somebody pls explain why this code does not give an exception
why this is compiling fine?
finally block
return stmt. in try/catch block