• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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: 24220
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: 24220
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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!