Sunday, August 15, 2010

Exceptions: Parser.java

Courtesy of Sun Web Learning Center

1. class Parser extends Utils {
2.   public static void main(String [] args) {
3.     try { System.out.print(new Parser().getInt("42"));
4.     }  catch (Exception e) {
5.       System.out.println("Exc"); }
6.   }
7.   int getInt(String arg) throws Exception {
8.     return Integer.parseInt(arg);
9.   }
10. }
11. class Utils {
12.   int getInt(String arg) { return 42; }
13. }

What is the result?

A     42
B     Exc
C     42Exc
D     Compilation fails.
E     An exception is thrown at runtime.

D is correct. You cannot add a checked exception to an overridden method.

No comments:

Post a Comment