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.
Joined: Nov 18, 2009
Thanks for your detailed explanation, Jelle.
Any other opinions?