0

The following code snippet is from the book OCA/OCP Java SE 7 Programmer 1 & 2 Study Guide by Kathy Sierra and Bert Bates.

    public void rethrow() throws SQLException, IOException {
    try {
        couldThrowAnException();
    } catch (Exception e) { // watch out: this isn't really
        // catching all exception sublclasses
        log(e);
        throw e; // note: won't compile in Java 6
    }
}

The text on page 393 states that "You may have noticed that couldThrowAnException() doesnt actually throw an exception. The compiler doesn't know this. The method signature is key to the compiler. It can't assume that no exception gets thrown, as a subclass could override the method and throw an exception."

Wouldn't that be incorrect or at least misleading cause a subclass cannot declare new or broader checked exceptions. Or am I missing something?

If so is the author referring to unchecked exceptions here? But then the compiler does not care about the unchecked exceptions one way or the other. I am missing the point being made here. Could someone please help me understand. Thanks.

Lauren
  • 3
  • 3
  • 1
    Not an exact duplicate, but contains your answer: http://stackoverflow.com/questions/5875414/why-cant-overriding-methods-throw-exceptions-broader-than-the-overriden-method – Daniel M. Aug 01 '16 at 17:39
  • The author means that just because this method catches an exception, doesn't mean a child has to. The compiler only sees the signature: `public void rethrow() throws SQLException, IOException`, and so it requires that these checked exceptions be caught when calling this method. – Zircon Aug 01 '16 at 17:39
  • The quoted text is about the method couldThrowAnException. I have edited my post and added that part in the quoted text now. The author says a subclass could override the method and throw an exception, which is why I was confused. The authors probably implied the method signature declared it threw an exception already and I thought the method signature didn't declare an exception already. Thanks for confirming that a subclass cannot throw broader or new checked exceptions still. – Lauren Aug 01 '16 at 17:55

0 Answers0