Should I declare all exceptions thrown from a method in the method signature or just the super class of the exceptions?

前端 未结 3 903
悲哀的现实
悲哀的现实 2021-01-14 16:08

When I throw checked exceptions from a method should I just declare the super class of the exceptions in the method signature or all the different types? If I have the follo

3条回答
  •  醉梦人生
    2021-01-14 16:28

    If the different sub types need different handling, then definitely declare the two different exceptions. Never expect the developer using your method to guess that you are actually throwing different types of exceptions.

    If you declare two distinct exceptions, and the user knows from the Javadoc that they are actually descendents of the same class, the user may choose to catch them both with a catch (SuperException e) rather than two individual catch clauses. But it depends on the user's choice.

    If you don't declare them separately, your IDE is not going to add the appropriate @Throws to your Javadoc comment. And your Javadoc will therefore only indicate that you're throwing SuperException, which will leave the user in the dark. Solving this by just putting it in the text of the comment is not a real solution. If any tool is using reflection to determine what your method throws, it will not see the individual exceptions in the array returned from Method.getExceptionTypes().

    If the functionality expected of the different exceptions is more or less the same and it's just a matter of how they will appear in the logs, it may be better to just use the parent exception, with different messages.

提交回复
热议问题