java 抛出什么异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3808310/
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
What exception to throw?
提问by nunos
I have a function which calculates the mean of a list passed as an argument. I would like to know which of Java exception should I throw when I try to compute the mean of a list of size 0.
我有一个函数可以计算作为参数传递的列表的平均值。我想知道当我尝试计算大小为 0 的列表的平均值时应该抛出哪个 Java 异常。
public double mean (MyLinkedList<? extends Number> list)
{
if (list.isEmpty())
throw new ????????; //If I am not mistaken Java has some defined exception for this case
//code goes here
}
Thanks.
谢谢。
回答by Colin Hebert
You can throw a new IllegalArgumentException()
.
你可以扔一个new IllegalArgumentException()
.
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
抛出以指示方法已传递非法或不适当的参数。
Just don't forget to pass a clear message as a first argument. This will really help you to understand what happend.
只是不要忘记传递一个明确的信息作为第一个参数。这将真正帮助您了解发生了什么。
For example "Can't use mean on an empty List".
例如“不能在空列表上使用均值”。
回答by Bert F
The question to ask yourself first is whether you should be throwing at all and then, if so, whether it should be a checked or unchecked exception.
首先要问自己的问题是您是否应该抛出异常,如果是,那么它应该是受检异常还是非受检异常。
Unfortunately, there's no industry best practice on deciding these things, as shown by this StackOverflow answer:
不幸的是,在决定这些事情上没有行业最佳实践,如这个 StackOverflow 答案所示:
In Java, when should I create a checked exception, and when should it be a runtime exception?
在 Java 中,我什么时候应该创建已检查的异常,什么时候应该创建运行时异常?
Nevertheless, there are some key considerations:
尽管如此,还是有一些关键的考虑因素:
Your design/vision for how this method is supposed to work (Is it reasonable/normal for the method to be called with 0-size list)?
Consistency with other methods in the class/package
Compliance with your applicable coding standard (if any)
您对此方法应该如何工作的设计/愿景(使用 0 大小列表调用该方法是否合理/正常)?
与类/包中其他方法的一致性
符合您适用的编码标准(如果有)
My opinion:
我的看法:
Return
Double.NAN
or 0If calling the method with a 0-size list is reasonable/expected/normal, I'd consider returningDouble.NAN
or0
if0
is appropriate for your problem domain.Throw an
IllegalArgumentException
If my design says that checking for an empty List is strongly the responsibility of the caller and the documentation for the method is going to clearly state that it is the responsibility of the caller, then I'd use the standard uncheckedIllegalArgumentException
.Throw a custom checked exceptionIf the method is part of a statistics package or library where several statistics functions need to deal with an possible empty data set, I'd think this is an exception condition that is part of the problem domain. I'd create a custom (probably checked) exception (e.g.
EmptyDataSetException
) to be part of the class/package/library and use it across all applicable methods. Making it a checked exceptions helps remind the client to consider how to handle the condition.
Return
Double.NAN
or 0如果使用 0 大小列表调用方法是合理的/预期的/正常的,我会考虑返回Double.NAN
或者0
是否0
适合您的问题域。抛出
IllegalArgumentException
如果我的设计说,检查空List强烈来电者的责任和方法的文档是要明确规定,这是调用者的责任,那么我会使用的标准选中IllegalArgumentException
。抛出自定义检查异常如果该方法是统计包或库的一部分,其中多个统计函数需要处理可能的空数据集,我认为这是属于问题域的异常条件。我会创建一个自定义(可能已检查)异常(例如
EmptyDataSetException
)作为类/包/库的一部分,并在所有适用的方法中使用它。使其成为已检查的异常有助于提醒客户端考虑如何处理该条件。
回答by John Engelman
You should create a new class that extends Exception and provides details specific to your error. For example you could create a class called EmptyListException that contains the details regarding your error. This couldbe a very simple exception class that takes no constructor arguments but maybe calls super("Cannot generate mean for an empty list");
to provide a custom message to the stack trace.
您应该创建一个新类来扩展 Exception 并提供特定于您的错误的详细信息。例如,您可以创建一个名为 EmptyListException 的类,其中包含有关您的错误的详细信息。这可能是一个非常简单的异常类,它不接受构造函数参数,但可能会调用super("Cannot generate mean for an empty list");
以向堆栈跟踪提供自定义消息。
A lot of times this isn't done enough...one of my most hated code smells is when developers use a generic exception (even sometimes Exception itself) and pass a string message into the constructor. Doing this is valid but makes the jobs of those implementing your code much harder since they have to catch a generic exception when really only a few things could happen. Exceptions should have the same hierarchy as objects you use for data with each level providing more specific details. The more detailed the exception class, the more detailed and helpful the stack trace is.
很多时候这还不够……我最讨厌的代码味道之一是当开发人员使用通用异常(甚至有时是异常本身)并将字符串消息传递给构造函数时。这样做是有效的,但会使那些实现您的代码的人的工作变得更加困难,因为他们必须在实际上只有少数事情可能发生时捕获通用异常。异常应该与您用于数据的对象具有相同的层次结构,每个级别都提供更具体的细节。异常类越详细,堆栈跟踪就越详细和有用。
I've found this site: Exceptional Strategiesto be very useful when creating Exceptions for my applications.
我发现这个站点:Exceptional Strategies在为我的应用程序创建异常时非常有用。
回答by hvgotcodes
IllegalArgumentException
非法参数异常
回答by Steven
How about NoSuchElementException. Although IllegalArgumentException might be better.
NoSuchElementException 怎么样。尽管 IllegalArgumentException 可能会更好。
回答by John Carter
Are you currently throwing any other exceptions (or planning to?) Any of the previously mentioned exceptions are fine, or just create your own. The most important thing is propagating the message of what went wrong.
您目前是否抛出任何其他异常(或计划抛出?)任何前面提到的异常都很好,或者只是创建自己的异常。最重要的是传播错误信息。
If there's a chance the 'catcher' of the exception might re-throw it, than you may want to investigate any other exceptions the 'catcher' might also throw.
如果异常的“捕获器”有可能重新抛出它,那么您可能想要调查“捕获器”也可能抛出的任何其他异常。
回答by BjornS
I am not convinced you should be throwing an exception there at all; the average of "nothing" is "nothing" or 0 if you will. If the set is empty, you should simply return 0.
我不相信你应该在那里抛出异常;如果您愿意,“无”的平均值是“无”或 0。如果集合为空,您应该简单地返回 0。
If you really MUST throw an exception, then IllegalStateException or IllegalArgumentException are your best choices.
如果您确实必须抛出异常,那么 IllegalStateException 或 IllegalArgumentException 是您的最佳选择。
回答by dty
How about an ArithmeticException - the same as the runtime throws.
ArithmeticException 怎么样 - 与运行时抛出相同。