Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions with Overriding

 
Bon Thanh
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bon Thanh
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your detailed explanation, Jelle.
Any other opinions?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic