Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try catch finally question

 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic