Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Return statement  RSS feed

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, pls check out the following code

class Test{

static String raid(){
try
{
throw new Exception();
}
catch (Exception e)
{
int i = 1 / 0 ;
return "Error";
}
finally
{
return "Peace";
}
}

public static void main(String args[]){
System.out.println(raid());
}
}


Questions:
1) what will happen to the exception(1/0) raised inside the catch block
2) is it is more than enough to have a return statement in a finally block
( i think so bcos any way it will get executed -- just to confirm)

thanks for the reply
 
author and iconoclast
Sheriff
Posts: 24219
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you return from a method from inside a finally block, any pending exceptions are discarded. The return in the finally will always be executed, and the return value of the function will be what is returned from the finally, even if the try or catch had already returned a value.

Many people consider this a flaw in the Java language definition -- it can certainly lead to some surprising behavior. you should never return from a finally -- it's a very bad practice.
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Ernest Friedman-Hill:
You should never return from a finally -- it's a very bad practice.


...or throw an exception.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24219
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Tony Morris:

...or throw an exception.



Or throw an exception.
 
Roses are red, violets are blue. Some poems rhyme and some don't. And some poems are a tiny ad.
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!