Wednesday, August 25, 2010

Overrides and Exceptions: Parser.java

Courtesy of Sun Web Learning Center


Given:

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) {
8.     return Integer.parseInt(arg);
9.   }
10. }
11. class Utils {
12.   int getInt(String arg) throws Exception { return 42; }
13. }

What is the result?


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

A is correct. It is legal for an overriding method to NOT throw the overridden method's exception.

No comments:

Post a Comment