signed

QiShunwang

“诚信为本、客户至上”

[Effective Java] Item 60: Favor the use of standard exception

2021/3/21 0:50:17   来源:

Commonly reused unchecked exceptions provided by Java platform libraries - 复用这些大家都知道的exceptions,好处就是大家都熟悉,容易理解,也知道这些异常所代表的用途。

The most commonly reused exceptions

ExceptionsOccasion for UseExample
IllegalArgumentExceptionNon-null parameter value is inappropriatepass a negative number in a parameter representing the number of times some action to be repeated
IllegalStateExceptionObject state is inappropriate for method invocationattempt to use some object before it is properly initialized
NullPointExceptionParameter value is null where prohibited
IndexOutofBoundsExceptionIndex parameter value is out of range
ConcurrentModificationExceptionConcurrent modification of an object has been detected where it is prohibitedan object that is designed by a single thread or with external synchronization detects that it is being concurrently modified
UnsupportedOperationExceptionObject does not support methodan append List implementation would throw this if someone tries to delete an element from the list

如果还有其它的exceptions符合你的需要,在符合exception java documentation的情况下,按照他的semantics意义来使用这些exception,而不是根据exception的名字。如果你要加一些failure-capture的信息,你也可以subclass这些异常。

最后选择异常,不是一个硬核科学,没有一个准数。某些情况,你可以发现有好几个上面举例的异常都能匹配,挑选一个比较合适的既可。