Java Exception Naming Conventions

2019-01-22 07:34发布

In Java, is there a semantic difference between using "Illegal" (as in IllegalArgumentException) versus "Invalid" (as in javax.activity.InvalidActivityException)?

During the course of an assignment it became useful to write a subclass of IllegalArgumentException to represent a series of input characters that cannot be tokenized, and I'm wondering whether convention says to use InvalidTokenException or IllegalTokenException.

The only difference I can find so far is that java.lang seems to prefer "Illegal" while javax.* prefers "Invalid". However, there is also java.security.InvalidParameterException which is a subclass of IllegalArgumentException.

3条回答
▲ chillily
2楼-- · 2019-01-22 08:08

You can have legal usage of an API and still have invalid data; it is all semantics.

查看更多
女痞
3楼-- · 2019-01-22 08:30

javax.activity.InvalidActivityException is inherited from java.rmi.RemoteException and you probably don't want this dependency. See also Javadoc

EDIT both Invalid and Illegal are used synonymously it makes no differency in semantics, just the technical issues mentioned above.

EDIT: From Postgres Documentation Section 45.3.14. Tricky words to avoid:

Illegal. "Illegal" stands for a violation of the law, the rest is "invalid". Better yet, say why it's invalid.

查看更多
叼着烟拽天下
4楼-- · 2019-01-22 08:32

AFAIK, IllegalArgumentException should only be used when you want to signal the incorrect use of an API method call. What it appears you are describing is a scenario when the API has been used incorrectly, so I think an IllegalArgumentException would be the better choice.

查看更多
登录 后发表回答