Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling Question from Dan Chisholm's mock exam

 
Lucy Das
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the question below, I am somehow missing the reason why the exception thrown by m5 (method 5) is not getting caught. The strange part is I changed the throws clause in the signature to "ColorException" and it still didn't catch it.
I know its something obvious but I just can't seem to put my finger on the spot.. Any help would be appreciated.
class ColorException extends Exception {}
class WhiteException extends ColorException {}
class White {
void m1() throws Exception {throw new ColorException();}
void m2() throws ColorException {throw new WhiteException();}
void m3() throws WhiteException {}
void m4() throws Exception {throw new Exception();}
void m5() throws WhiteException {throw new WhiteException();}
void m6() {}
public static void main (String[] args) {
White white = new White();
char a,b,c,d,f,g,h,i;
a = b = c = d = f = g = h = i = 'a';
try {
try {white.m1();} catch (ColorException e) {a++;} h++;
try {white.m2();} catch (ColorException e) {b++;} h++;
try {white.m3();} catch (ColorException e) {c++;} h++;
try {white.m4();} finally {d++;}
try {white.m5();} catch (ColorException e) {f++;} finally {h++;}
try {white.m6();} catch (Exception e) {g++;} finally {h++;}
} catch (Exception e) {i++;}
System.out.println(a+","+b+","+c+","+d+","+f+","+g+","+h+","+i);
}
}

What is the result of attempting to compile and run the above program?
a. Prints: b,b,a,b,a,a,d,b
b. Prints: b,b,a,b,a,a,f,b
c. Prints: b,a,a,a,a,a,a,b
d. Prints: b,a,a,b,a,a,c,b
e. Prints: b,b,a,a,b,a,f,b
f. Prints: b,b,b,a,b,b,f,b
g. Runtime Exception
h. Compiler Error
i. None of the Above
The answer is a
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please note that you have try blocks inside the "main" try block, but not all of them have a corresponding catch block. In your "main" try block

m4() throws an exception which is not caught by an "inner" catch block. The thread of execution is now therefore interrupted and the error propagates outward, and is caught by the "main" catch block. Methods m5() and m6() are not called.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic