java 尝试插入重复键时抛出的正确异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6636371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:43:53  来源:igfitidea点击:

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

javaexception-handling

提问by Robert Oschler

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

我反复看到关于避免抛出泛型的评论RuntimeException,我正在努力遵循该准则。

I have a class that aggregates a SortedMapwith 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.

我有一个类将 aSortedMap与属性设置聚合在一起,以允许或禁止重复键。我试图弄清楚当不允许重复键并尝试添加一个时我应该抛出什么异常。

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

我检查了Exception该类的 Java 文档,没有一个已知的直接后代似乎适合。EDuplicateMapKey例如,我是否只是继续创建自己的类并抛出它?如果是这样,我如何避免以一大堆类文件结束,每个自定义Exception类型一个?

What is considered "best practice" here?

这里什么被认为是“最佳实践”?

采纳答案by Marcelo

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

创建您自己的例外。例如,Java EE 具有DuplicateKeyException,您可以执行与自定义地图类似的操作。

回答by skaffman

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

例如,我是否继续创建我自己的 EDuplicateMapKey 类并抛出它?

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.

绝对没错。如果感觉是正确的方法,不要害怕创建新的异常类型。如果作为作者的您不清楚使用哪种异常类型是正确的,那么使用您的 API 的程序员肯定不会清楚。所以让它明确,并创建你自己的异常类型。

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.

异常类与任何其他业务逻辑类型没有什么不同。在创建“正常”代码所需的尽可能多的类型时,您不会感到受到限制(至少,我希望您不要这样做),并且在涉及异常类型时应该不会有什么不同。它们通常同样重要。

回答by Andrew White

Personally, IllegalStateExceptionor IllegalArgumentExceptionlooks like it could work here but I can see arguments against that too.

就个人而言IllegalStateExceptionIllegalArgumentException看起来可以在这里工作,但我也可以看到反对它的论据。