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

前端 未结 3 910
悲哀的现实
悲哀的现实 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:32

    The interface should be as stable as possible. So probably Super. Many libraries use the "Super" strategy, because exception specs cause far more annoyance in maintainability than readability or safety they add. Even the IOException is a Super that nearly all Java library code uses instead of declaring more specific exceptions. (But when they do declare more specific exceptions, it's because the contract is that more general IOExceptions won't be thrown. Read on.)

    You might list Sub1 and Sub2 if you really do want to say each of those exceptions can be thrown, but don't want to say that any derivative of Super can be thrown. Perhaps Sub1 is NumberCrunchException and your method calls crunchNumbers() and users of your method can be assured that's the only exception-ful thing your method does. In that case the specific strategy is better.

提交回复
热议问题