Page: 5
5. Exception Handling
22. Given:
class Emu {
static String s = "-";
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
try { throw new Exception();
} catch (Exception ex) { s += "ic "; }
throw new Exception(); }
catch (Exception x) { s += "mc "; }
finally { s += "mf "; }
} finally { s += "of "; }
System.out.println(s);
} }
What is the result?
A. -ic of
B. -mf of
C. -mc mf
D. -ic mf of
E. -ic mc mf of
F. -ic mc of mf
G. Compilation fails.
Answer:
-> E is correct. There is no problem nesting try / catch blocks. As is normal, when an exception is thrown, the code in the catch block runs, then the code in the finally block runs.
-> A, B, C, D, and F are incorrect based on the above.
(Objective 2.5)
23. Given:
class Mineral { }
class Gem extends Mineral { }
class Miner {
static int x = 7;
static String s = null;
public static void getWeight(Mineral m) {
int y = 0 / x;
System.out.print(s + " ");
}
public static void main(String[] args) {
Mineral[] ma = {new Mineral(), new Gem()};
for(Object o : ma)
getWeight((Mineral) o);
}
}
And the command-line invocation:
java Miner.java
What is the result?
A. null
B. null null
C. A ClassCastException is thrown.
D. A NullPointerException is thrown.
E. A NoClassDefFoundError is thrown.
F. An ArithmeticException is thrown.
G. An IllegalArgumentException is thrown.
H. An ArrayIndexOutOfBoundsException is thrown.
Answer:
-> E is correct. The invocation should be java Miner, in which case null null would be produced.
-> A, B, C, D, F, G, and H are incorrect based on the above.
24. Which are most typically thrown by an API developer or an application developer as opposed to being thrown by the JVM? (Choose all that apply.)
A. ClassCastException
B. IllegalStateException
C. NumberFormatException
D. IllegalArgumentException
E. ExceptionInInitializerError
Answer:
-> B , C, and D are correct. B is typically used to report an environment problem such as trying to access a resource that’s closed. C is often thrown in API methods that attempt
to convert poorly formed String arguments to numeric values. D is often thrown in API
methods that receive poorly formed arguments.
-> A and E are thrown by the JVM.
Page: 5
1
2
3
4
5