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

1

7

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
}
Isaisaac answered 17/3, 2015 at 22:44 Comment(1)
because JVM can propagate the exceptionMagnetize
G
12
  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.
Gyrose answered 17/3, 2015 at 22:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.