• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

An Exception Problem

 
SimonJ Birch
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

I've just worked my way through the problem below from the K & B study guide SJCP 5:

8. Given:
1. class Ping extends Utils {
2. public static void main(String [] args) {
3. Utils u = new Ping();
4. System.out.print(u.getInt(args[0]));
5. }
6. int getInt(String arg) {
7. return Integer.parseInt(arg);
8. }
9. }
10. class Utils {
11. int getInt(String x) throws Exception { return 7; }
12. }
And the following three possible changes:
C1. Declare that main() throws an Exception.
C2. Declare that Ping.getInt() throws an Exception.
C3. Wrap the invocation of getInt() in a try / catch block.
Which change(s) allow the code to compile? (Choose all that apply.)
A. Just C1 is sufficient.
B. Just C2 is sufficient.
C. Just C3 is sufficient.
D. Both C1 and C2 are required.
E. Both C1 and C3 are required.
F. Both C2 and C3 are required.
G. All three changes are required.


I can't understand why the correct answers are A and C (my choice was C). I can't follow their reasoning either for the answer!

Can anyone explain the rationale behind the answer?

Thanks

Simon
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two things a method can do with a checked exception:

1. The code in a method that throws a checked exception must declared the exception at the throws clause in its method definition (i.e., declare any exception which it throw) , and
2. The code in a method that calls a method that throws a checked exception must either be inside a try block with a catch clause for that exception or must in turn declare that exception in its own throws clause.
 
SimonJ Birch
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply, Wise

I guess where I am getting confused is in my understanding of the phrase 'Wrap the invocation of getInt() in a try / catch block'. Which line is this referring to?
 
SimonJ Birch
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am also confused by 'Declare that Ping.getInt() throws an Exception' as I can see no method call named Ping.getInt() in the program.
 
SimonJ Birch
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thought.....I thought that the main method would be at the bottom of the call stack and therefore couldn't declare a throws exception. Or does it simply throw the exception to the superclass, in this case Utils?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic