Friday, February 3, 2012

Tricky Java exceptions quiz

If you think you know everything about throwing and handling exceptions in Java, try to find the right answer for this couple of questions I have come across. You can find the right answers at the end of this post, or by testing it on your own computer.

Question 1. What exception will be thrown from the following block of code?

try {
throw new TryException();
}
catch {
throw new CatchException();
}
finally {
throw new FinallyException();
}

a) TryException
b) CatchException
c) FinallyException

Question 2. We know that the method printStackTrace of an exception prints the stack of methods that have been call when that exception has ocurred. What stack trace will be printed after calling method1?

public void method1() throws Exception {
method2();
}

public void method2() throws Exception {
throw method3();
}

public Exception method3() {
return new Exception();
}

a)
Exception in thread "main" java.lang.Exception
at mypackage.MyClass.method3(MyClass.java:30)
...
b)
Exception in thread "main" java.lang.Exception
at mypackage.MyClass.method2(MyClass.java:20)
...

c)
Exception in thread "main" java.lang.Exception
at mypackage.MyClass.method1(MyClass.java:10)
...

Right answers