Java Exception Naming Conventions

五迷三道 提交于 2019-12-29 03:36:06

问题


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.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2364217/java-exception-naming-conventions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!