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

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

    A general rule of implementing and extending is you can make your new class or interface "less restrictive" but not "more restrictive". If you think of the requirement to handle an exception as a restriction, an implementation that doesn't declare the exception is less restrictive. Anybody who codes to the interface will not have trouble with your class.

    — Stan James


    As part of the discussion at http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface

提交回复
热议问题