aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes An Exception Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "An Exception Problem" Watch "An Exception Problem" New topic
Author

An Exception Problem

SimonJ Birch
Greenhorn

Joined: Jun 01, 2006
Posts: 10
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

Joined: Feb 02, 2006
Posts: 2023
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

Joined: Jun 01, 2006
Posts: 10
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

Joined: Jun 01, 2006
Posts: 10
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

Joined: Jun 01, 2006
Posts: 10
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?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: An Exception Problem