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

前端 未结 3 792
慢半拍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:24

    Great answer by @Chetter Hummin.

    One way to look at this, and I find it easy to remember, is interface's implementations can be more specific but not more general.

    For example in interface void test() throws Exception means "test may throw exception"

    then implementation can be void test() means "test will not throw exception" (more specific)

    or implementation can be void test() throws NullpointerException (more specific)

    interface x {
        void testException() throws Exception;
    }
    
    public class ExceptionTest implements x {
        @Override
        public void testException() {   //this is fine
        }
    
        ////// or
    
        @Override
        public void testException() throws NullPointerException {  // this is fine
        }
    }
    

提交回复
热议问题