File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exceptions with Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exceptions with Overriding" Watch "Exceptions with Overriding" New topic
Author

Exceptions with Overriding

Bon Thanh
Greenhorn

Joined: Nov 18, 2009
Posts: 17
This is a question from the ePractice exams for 310-055 purchased directly from Sun Microsystems.

Given:



What is the result?

A - 42
B - Compilation fails.
C - No output is produced.
D - An exception is thrown at runtime.

Sun's answer is:
Option A is correct. The overriding method is safer, and parseInt can throw only a runtime exception.

I don't understand what is meant by the term "safer" in this context. Can someone please clarify?

Thank you!
Bonnie
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1794
    
    7

It's legal for an overriding method to omit an exception specification for the method it overrides.
In other words, it's legal for an overriding method to specify fewer exceptions than the method it overrides, or in fact specify no exceptions at all.

In this particular code snippet the getInt() implementation in the Utils class specifies that it can throw anything that IS-A java.lang.Exception, so it basically says: "If you call me, all bets are off and you'd better be prepared to handle anything that IS-A java.lang.Exception!"
Whereas the getInt() implementation in the Parser class overrides the Utils class' getInt() implementation and basically says: "You know what, I'm absolutely certain MY implementation is super-safe and will NEVER throw anything that IS-A java.lang.Exception!".
So in that regard the Parser class'getInt() implementation seems safer.

In practice it's the Utils class' implementation that is 100% safe, whereas the Parser class' implementation may fail horribly at run-time, if the String it passes to Integer.parseInt() can't be parsed to an integer. It will then throw a java.lang.NumberFormatException, which it didn't specify ever throwing! That's legal only because java.lang.NumberFormatException IS-A java.lang.RuntimeException, which isn't subject to the catch-or-specify rule.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Bon Thanh
Greenhorn

Joined: Nov 18, 2009
Posts: 17
Thanks for your detailed explanation, Jelle.
Any other opinions?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exceptions with Overriding