File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Exception Handling Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception Handling Query" Watch "Exception Handling Query" New topic

Exception Handling Query

prerna boja
Ranch Hand

Joined: Aug 19, 2004
Posts: 67
Hi all,

I have the following program

when x= 1 the switch jumps tp case 1 and line (2) is executed and goes to
// line (6) and then d=1. My doubt is The nested catch clause will catch a Level1Exception or any subclass of it. So Level2Exception should also be caught and then b should be equal to 1 .But when I run the program b is not incremented ?. ofcourse all finally block runs so c=g=1.

I have one more question when x=3 it // line (7) should be executed but the result is same as when x=2. why is it so.

please expain me where am I going wrong.

Thanks in advance.

[EJFH: Added CODE tags ]
[ February 22, 2005: Message edited by: Ernest Friedman-Hill ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

(I added CODE tags to your code -- see how nice it looks now? On the message-entry screen, look at the "Instant UBB Code" buttons.)

OK, now -- the nested catch clause won't catch Level1Exception and all subclasses, it will catch Level2Exception and all subclasses. But when x is 1, a Level1Exception is thrown, and the nested catch block is not used.

Now, when x is 2, that catch block is indeed used; but then the outer one isn't. If you want the outer one to catch an already-caught exception, then the inner-catch block has to re-throw the exception -- i.e.,

catch (Level2Exception e) {b++; throw e;}

Once you catch an exception, unless you rethrow it, it's "dead". It can't be caught again.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Exception Handling Query
It's not a secret anymore!