Why can a method be declared to throw many exceptions even if none of them are thrown?

I was merging my source code with that of a colleague and I saw he had added an exception to be thrown in the declaration of a method; however, I knew, that exception would never be really thrown from that method.

I wonder why the compiler did not warn me about a "non-thrown exception declared" (or something like that). I realize that you can declare a method throwing N exceptions, even if none of those exceptions is thrown by the code in the method.

Why is that?

public void foo() throws IOException, IntrospectionException,  BadStringOperationException, ... {
    //do nothing
}

Upvotes: 7

Views: 132

Answers (1)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26559

  1. Subclasses that override the method may throw the exception, even if its superclass doesn't.
  2. You can later change the method to throw one of the listed exceptions while maintaining backwards compatibility.

Upvotes: 12

Related Questions