• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Returning value in finally block

 
Ranch Hand
Posts: 415
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

Why won't java allow to return a value in finally block ??

public static void main(String[] args)
{
System.out.println("Method output is:"+ getValue());
}

public static boolean getValue()
{
try
{
return true;
}
catch(Exception e)
{
return false;
}
finally
{
return true; Here compilation error occurs
}
}

Is it that returning in finally overwrites the value returned in the catch block if the exception occurs ??
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried placing your code in a class definition and compiling it, and it compiles with the return in finally.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This method will compile fine according to the Java Language Spec -- there's no error here. But I'm sure that some compilers and especially some IDEs will give you a warning, because returning a value from "finally" is almost always the wrong thing to do because, as you have alluded to, that return "cancels" any previous returns, and also hides any exceptions that might have been thrown.
 
It's never done THAT before. Explain it to me tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic