Correct Exception to throw when a duplicate key insertion is attempted?

五迷三道 提交于 2019-12-12 10:42:52

问题


Repeatedly I see comments about avoiding throwing generic RuntimeException and I am trying to follow that guideline.

I have a class that aggregates a SortedMap with a property setting to allow or disallow duplicate keys. I am trying to figure out what Exception I should throw when duplicate keys are disallowed and an attempt is made to add one.

I checked the Java docs for the Exception class and none of the known direct descendants seemed suitable. Do I just go ahead and create my own EDuplicateMapKey class for example and throw that? If so, how do I avoid ending up with a big pile of class files, one for each custom Exception type?

What is considered "best practice" here?


回答1:


Create your own exception. For example Java EE has DuplicateKeyException, you can do something similar as that for your custom map.




回答2:


Do I just go ahead and create my own EDuplicateMapKey class for example and throw that?

Absolutely, yes. DOn't be afraid to create new exception types if it feels like the right way to go. If it's not clear to you, as the author, which is the right exception type to use, then it certainly won't be clear to the programmer using your API. So make it explicit, and create your own exception type.

How do I avoid ending up with a big pile of class files, one for each custom Exception type?

Exception classes are no different to any other business logic type. You don't feel restrained in creating as many types as you feel is necessary for your "normal" code (at least, I hope you don't), and you should feel no differently when it comes to exception types. They're often just as important.




回答3:


Personally, IllegalStateException or IllegalArgumentException looks like it could work here but I can see arguments against that too.



来源:https://stackoverflow.com/questions/6636371/correct-exception-to-throw-when-a-duplicate-key-insertion-is-attempted

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