Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dan exam doubt 15

 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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++;}
System.out.print(a+","+b+","+c+","+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
 
Giovanni De Stefano
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

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 ]
 
Adam Czysciak
Ranch Hand
Posts: 90
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, I agree to what Adam says
Change ur code to:
-------------------


Now check out the behaviour
No compilation error
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic