File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes dan exam doubt 15 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "dan exam doubt 15" Watch "dan exam doubt 15" New topic

dan exam doubt 15

amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 812
hii in one question

class RedException extends Exception {}
class BlueException extends Exception {}
class White {
void m1() throws RedException {throw new RedException();}
public static void main (String[] args) {
White white = new White();
int a,b,c,d; a = b = c = d = 0;
try {white.m1(); a++;}
catch (RedException e) {b++;}
catch (BlueException e) {c++;}
finally {d++;}

What is the result of attempting to compile and run the program?

a. Prints: 0,1,0,0
b. Prints: 1,1,0,1
c. Prints: 0,1,0,1
d. Prints: 0,1,1,1
e. Prints: 1,1,1,1
f. Compile-time error
g. Run-time error
h. None of the above

with answer : "f" with explanation ...
A compile-time error is generated, because the second catch clause attempts to catch an exception that is never thrown in the try block.

didn't get the point ??

..pls explain

Thanks and Regards, Amit Taneja
Giovanni De Stefano
Ranch Hand

Joined: Aug 17, 2004
Posts: 154

The idea is supposed to be this: you can catch exceptions of the type declared in the method signature OR other types that BELONG to the same hierarchy of the type declared in the method signature.

In your example, the two exceptions don't belong to the same hierarchy. That's why you get a compiler error.

I hope this makes sense.

Gio :-)
[ February 24, 2005: Message edited by: Giovanni De Stefano ]

SCJP 1.4
Adam Czysciak
Ranch Hand

Joined: Feb 25, 2005
Posts: 90
Both your exceptions are checked exceptions. When you want to catch a checked exception, your try block must be this exception (or any of its superclasses) throwable. In other words - any of the statements in the try block must be declared to throw this exception. Your blue exception is not defined in m1, therefore it can't be catched.

Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
Yeah, I agree to what Adam says
Change ur code to:

Now check out the behaviour
No compilation error
I agree. Here's the link:
subject: dan exam doubt 15
It's not a secret anymore!