• Post Reply Bookmark Topic Watch Topic
  • New Topic

Awkward Question from Exception  RSS feed

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
In the below Code,It suppose to throw an exception.Rather than its returning an value.I knew because of finally block.But what about the Exception which has thrown by the code ( Lable Throw Exception ),it suppose to be reaches the user,isn't it?.
Please expalin,where the thrown exception gone.
class TestingFinally
{
void int testingFinally() throws Exception{
try{
System.out.println("1");
throw new RuntimeException();//Lable Throw Exception
}catch(RuntimeException e){
System.out.println("2");
throw new Exception();
}catch(Exception e){
System.out.println("3");
throw new Exception();
}finally{
System.out.println("4");
return 10;
}
}
public static void main(String[] args) throws Exception
{
System.out.println("Hello World!");
System.out.println(new TestingFinally().testingFinally());
System.out.println("Hello World!");
}
}
 
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 finally block, it "cancels" any thrown exceptions, and supercedes any previous return values from try or catch blocks. As a general rule, never use "return" in a finally block.
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Returning a value or throwing an exception from within a finally block is a BIG no-no.
There is never a good reason or justification to violate this rule.
A tool called CheckStyle might assist you in prevention of such fundamental errors in the future.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple of other things I noticed:
- Declaring to throw java.lang.Exception or catch java.lang.Exception is generally an abuse of the Java exception handling mechanism, although there are several justifications for doing so since you will also be handling exception of type java.lang.RuntimeException which is A Bad Idea(TM).
- void int testingFinally() throws Exception
This won't compile with two return types.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!