Java interface throws an exception but interface implementation does not throw an exception?

前端 未结 3 786
慢半拍i
慢半拍i 2020-11-30 20:57

I read this code where the interface throws an exception, but the class which implements it doesn\'t throw one or catch one, why is that? Is it legal or safe in java?

3条回答
  •  隐瞒了意图╮
    2020-11-30 21:30

    If a Java method overrides another in a parent class, or implements a method defined in an interface, it may not throw additional checked exceptions, but it may throw fewer.

    public class A {
        public void thrower() throws SQLException {...}
    }
    
    public class B extends A {
        @Override
        public void thrower() throws SQLException, RuntimeException, NamingException {...}
    }
    

    SQLException is fine; it's declared in the overridden method. It could even be replaced by a subclass like SerialException.

    RuntimeException is fine; those can be used anywhere.

    NamingException is illegal. It isn't a RuntimeException, and isn't in A's list, even as a subtype.

提交回复
热议问题