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
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception