0

In Java you can write a class like

public class Test {
    public static void main(String[] args) throws IOException {
        System.out.println("Hello World!");
    }
}

In here we have a main method that declares it is throwing an IOException (which is checked) even though it is clearly not possible for this to happen.

As far as I can tell it is easy for the compiler to tell what checked exceptions a method can throw. Therefore it should be easy to throw a compiler error saying 'this method can not throw an IOException'.

Is there some corner case I'm not thinking of where a checked exception can be thrown without the compiler realizing it? Or is there some other reason why methods must be allowed to declare throws that they will never be able to throw?

David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
  • In general: subclasses might override the method, and _their_ implementation might throw. (That doesn't exactly apply to static methods, though.) – Louis Wasserman Sep 14 '17 at 01:25
  • Someone's probably going to dig up a super-precise answer but I suspect what it boils down to is that `throws Checked` is part of the method signature that's a contract for the caller, not the implementation. It doesn't seem worth checking because there is no way a compiler can really check a method really throws such an exception, even if it appears to. – pvg Sep 14 '17 at 01:25

0 Answers0