File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes try catch finally question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "try catch finally question" Watch "try catch finally question" New topic
Author

try catch finally question

mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
why does finally require a return as well ?
this is the compile error:
: Return required at end of long amethod
static long amethod()
what is the rule here ? i believe try block takes care of what the calling method return type is. and finally block is for things like "any clean-up code". (quoting from KM). nowhere does it say that finally too has to take care of the return type of the calling method.
class Test {
public static void main(String args[])
{ amethod(); }
static long amethod()
{
try{return 1;}
catch(Exception e){System.out.println("Caught Exception");}
finally{System.out.println("finally executed");}}
}
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
Hi Mark!
Try this code:

The error message is not about return from finally, it is from the end of the method.
If your try block runs successfully there has to be another return point from the function.
I hope this helps,
Brian
PS - Oops I forgot to mention the main point I was trying to convey. Try block has the capability to exiting abnormally/abruptly and hence the compiler tries to ensure you have a valid return statement from the method.
I also added the println statement so you can better understand what's going on.
PPS - Read my posts after 20 minutes from my original post time - this way you will get a better response. I am just learning to post at javaranch
[ February 08, 2002: Message edited by: Brian Lugo ]
[ February 08, 2002: Message edited by: Brian Lugo ]
Rajinder Yadav
Ranch Hand

Joined: Jan 18, 2002
Posts: 178
Mark, note that you declared "amethod" to return a long value,
static long amethod()
so the compiler error was complaining that a return statement was missing! btw, the 2nd possible fix would be to declared "amethod" to have no return value like so,
static void amethod()
then you would not need the return statement.


<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try catch finally question