• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

strange behavior of Exception

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Would anyone please clarify the behavior of the following code?
I am trying to use try/finally statement to handle exception thrown.
class AException extends Exception {
}
class BException extends Exception {
}
public class ExceptionTest2 {
public void aMethod() throws BException{
try {
throw new AException();
}
finally {
System.out.println("AException thrown");
throw new BException();
}
}

}
In try block, AExceptin is thrown, and in finally block, BException is thrown. This file compiles ok.
My question is:
1.why isn't "AException" required in throws clause
2. strangly, if BException is not thrown in finally(no exception thrown in finally), then this code cannot be compiled. and compiler asks AException in try block be handled or declared.
Why is it?
thanks
 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Answer for ur Q1. lies in your Q2.
Checked exceptions declared as throws XX in a method declaration should be exactly thrown by the body of the method. You can't just say, i will come to London and be without going to London. Like that, if you didn't throw the checked exception in the body, compiler will fire at you. well thats not the problem u asked for!!. Here, u r throwing AException, but throwing BException in the finally bloc. This makes the previous unhandled Exceptions to just go escape and the method overall throws BException (which is not handled in the finally bloc) from its body. So declaring throws BException worked.
Now coming to second Q. if u commented that throws BException statement in the finally bloc, and declaring that u r throwing BException, it is similar that u say somebody u will come to Frankfurt and they are waiting there to receive u and u go to London and nobody is there to receive u. Similarly u throw AException (a checked one), but declare thrwos BException.

HTH.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic