Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic