• Post Reply Bookmark Topic Watch Topic
  • New Topic

Return statement  RSS feed

 
Raj Kumar
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
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
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.
 
Tony Morris
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: 24217
38
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!