Java 什么时候抛出运行时异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27538706/
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-08-11 04:33:16  来源:igfitidea点击:

When to throw runtime exception?

javaexception

提问by user2430771

Recently, I had interview with company and they gave me a coding problem. I was given program related to deck of cards and one of the methods was to shuffle the deck of cards. So I wrote the program as:

最近,我面试了公司,他们给了我一个编码问题。我得到了与纸牌相关的程序,其中一种方法是洗牌。所以我把程序写成:

/** Shuffle the list of cards so that they are in random order 
 * @param d Deck of cards*/
public  static void shuffle(Deck d)
{
    if(d == null)
        throw new IllegalArgumentException();
    Random randomGenerator = new Random();
    List<Card> cards = d.getDeckOfCards();   // cards is basically Linked List.. cards = new LinkedList<Cards>()
    for(int i=0;i<cards.size();i++)
    {
        int randomNumber = randomGenerator.nextInt(52);
        Card c1 = cards.remove(randomNumber);
        Card c2 = cards.remove(0);
        cards.add(0, c1);
        cards.add(randomNumber,c2);
    }       

}

In the above code, I have thrown IllegalArgumentExceptionwhich I'm most doubtful about. Under what conditions should actually throw a runtime exception? Should we actually throw runtime exception?

在上面的代码中,我抛出了我最怀疑的IllegalArgumentException。在什么情况下应该真正抛出运行时异常?我们真的应该抛出运行时异常吗?

Thanks

谢谢

采纳答案by dasblinkenlight

Should we actually throw runtime exception?

我们真的应该抛出运行时异常吗?

Yes, we should. Runtime exception serve a specific purpose - they signal programming problems that can be fixed only by changing code, as opposed to changing the environment in which the program runs.

是的,我们应该。运行时异常服务于特定目的 - 它们表示只能通过更改代码来修复的编程问题,而不是更改程序运行的环境。

Under what conditions should actually throw a runtime exception?

在什么情况下应该真正抛出运行时异常?

When you detect an error with the way your class or method is used, throw a runtime exception.

当您使用类或方法的使用方式检测到错误时,抛出运行时异常。

Generally, there are two categories of situations when you need to throw a runtime exception:

一般来说,需要抛出运行时异常有两种情况:

  • Passing invalid parameter values- This is the most common cause of runtime exceptions. Most parameter validation exceptions should be runtime exceptions. Java provides several subclasses to signal these specific problems.
  • Calling methods in a wrong sequence- This is another common cause. When certain methods cannot be called until a class finishes initialization or some other preparatory steps, calls at the wrong time should cause runtime exceptions.
  • 传递无效参数值- 这是运行时异常的最常见原因。大多数参数验证异常应该是运行时异常。Java 提供了几个子类来表示这些特定问题。
  • 以错误的顺序调用方法- 这是另一个常见原因。当某些方法在类完成初始化或其他一些准备步骤之前无法调用时,在错误的时间调用应该会导致运行时异常。

In this sense, your code is fine: it fits squarely in the first category, i.e. passing invalid parameter values. One thing I would do slightly differently is adding a message to say which parameter had an invalid value, but in your case it is not critical, because there is only one parameter there.

从这个意义上说,您的代码很好:它完全适合第一类,即传递无效的参数值。我会稍微不同的一件事是添加一条消息,说明哪个参数的值无效,但在您的情况下,这并不重要,因为那里只有一个参数。

回答by Doorknob

IllegalArgumentExceptionis, in fact, a subclass of RuntimeException.

IllegalArgumentException实际上是 的一个子类RuntimeException

It's just better to be a bit more specific, to help other programmers in the future. I would definitely prefer the IllegalArgumentExceptionbecause it best describes what exactly went wrong, but really, either one would work.

最好更具体一点,以帮助将来的其他程序员。我肯定更喜欢 ,IllegalArgumentException因为它最好地描述了到底出了什么问题,但实际上,任何一个都可以。

回答by Ankur Singhal

For example, if you're reading a file , and some IO error occurs, you're unlikely to recover from the error, so re-throwing the error to the top and consequently terminating the application isn't a bad course of action.

例如,如果您正在读取一个文件,并且发生了一些 IO 错误,则您不太可能从错误中恢复,因此将错误重新抛出到顶部并因此终止应用程序并不是一个糟糕的操作过程。

On the other hand, if you're anticipating recoverable errors then you should absolutely catch and handle the errors. For example, you may have users entering data in a form. If they enter data incorrectly, your input processing code may throw an exception (e.g. NumberFormatExceptionwhen parsing a malformed number string). Your code should catch these exceptions and return an error the user, prompting for correct input.

另一方面,如果您预计会出现可恢复的错误,那么您绝对应该捕获并处理这些错误。例如,您可能让用户在表单中输入数据。如果他们输入的数据不正确,您的输入处理代码可能会抛出异常(例如,NumberFormatException在解析格式错误的数字字符串时)。您的代码应该捕获这些异常并向用户返回错误,提示输入正确。

When catching an exception and throwing RuntimeExceptioninstead, it is important to set the original exception as a cause for the RuntimeException. i.e.

当捕获异常并抛出时RuntimeException,重要的是将原始异常设置为 RuntimeException 的原因。IE

throw new RuntimeException(originalException).

扔新的RuntimeException(originalException)