简体   繁体   English

抛出什么例外?

[英]What exception to throw?

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. 谢谢。

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". 例如“不能在空列表中使用均值”。

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)? 您对此方法应如何工作的设计/愿景(使用0大小列表调用方法是否合理/正常)?

  • Consistency with other methods in the class/package 与类/包中的其他方法保持一致

  • Compliance with your applicable coding standard (if any) 符合您的适用编码标准(如果有)

My opinion: 我的看法:

  • Return Double.NAN or 0 If calling the method with a 0-size list is reasonable/expected/normal, I'd consider returning Double.NAN or 0 if 0 is appropriate for your problem domain. 返回Double.NAN或0如果调用具有0大小列表的方法是合理的/预期的/正常的,我会考虑返回Double.NAN0如果0适合您的问题域。

  • 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 unchecked IllegalArgumentException . 抛出IllegalArgumentException如果我的设计说检查一个空的List是调用者的强烈责任,并且该方法的文档将明确指出它是调用者的责任,那么我将使用标准的未经检查的IllegalArgumentException

  • Throw a custom checked exception If 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 (eg EmptyDataSetException ) to be part of the class/package/library and use it across all applicable methods. 我将创建一个自定义(可能已检查)异常(例如EmptyDataSetException )作为类/包/库的一部分,并在所有适用的方法中使用它。 Making it a checked exceptions helps remind the client to consider how to handle the condition. 将其作为已检查的异常有助于提醒客户考虑如何处理该情况。

You should create a new class that extends Exception and provides details specific to your error. 您应该创建一个扩展Exception的新类,并提供特定于您的错误的详细信息。 For example you could create a class called EmptyListException that contains the details regarding your error. 例如,您可以创建一个名为EmptyListException的类,其中包含有关错误的详细信息。 This could be a very simple exception class that takes no constructor arguments but maybe calls super("Cannot generate mean for an empty list"); 可能是一个非常简单的异常类,它不带构造函数参数,但可能调用super("Cannot generate mean for an empty list"); to provide a custom message to the stack trace. 向堆栈跟踪提供自定义消息。

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. 很多时候这个做得还不够......我最讨厌的代码之一就是当开发人员使用泛型异常(甚至有时是Exception本身)并将字符串消息传递给构造函数时。 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 Strategies to be very useful when creating Exceptions for my applications. 我发现这个网站:在为我的应用程序创建例外时非常有用的特殊策略

抛出:IllegalArgumentException

How about NoSuchElementException. NoSuchElementException如何? Although IllegalArgumentException might be better. 虽然IllegalArgumentException可能会更好。

ArithmeticException如何 - 与运行时抛出相同。

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. 如果异常的'捕手'有可能重新抛出它,那么你可能想要调查任何其他例外,'捕手'也可能抛出。

I am not convinced you should be throwing an exception there at all; 我不相信你应该在那里抛出一个例外; the average of "nothing" is "nothing" or 0 if you will. “没有”的平均值是“无”或0如果你愿意。 If the set is empty, you should simply return 0. 如果集合为空,则只需返回0。

If you really MUST throw an exception, then IllegalStateException or IllegalArgumentException are your best choices. 如果你真的必须抛出一个异常,那么IllegalStateException或IllegalArgumentException是你最好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM