什么时候抛出运行时异常? [英] When to throw runtime exception?
问题描述
最近,我接受了公司的采访,他们给了我一个编码问题。我得到了与纸牌有关的程序,其中一种方法是将纸牌洗牌。因此,我将该程序编写为:
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);
}
}
在上面的代码中,我有引发了我最怀疑的 IllegalArgumentException 。在什么情况下实际上应该抛出运行时异常?
In the above code, I have thrown IllegalArgumentException which I'm most doubtful about. Under what conditions should actually throw a runtime exception? Should we actually throw runtime exception?
谢谢
推荐答案
实际上应该抛出运行时异常吗?
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:
- 传递无效的参数值-这是运行时异常的最常见原因。大多数参数验证异常应为运行时异常。 Java提供了几个子类来表示这些特定问题。
- 以错误的顺序调用方法-这是另一个常见原因。如果在类完成初始化或其他一些准备步骤之前无法调用某些方法,则在错误的时间调用会导致运行时异常。
- 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.
从这个意义上讲,您的代码很好:它正好适合第一类,即传递无效的参数值。我要做的事情略有不同,就是添加一条消息,说明哪个参数的值无效,但是在您的情况下这并不重要,因为那里只有一个参数。
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.
这篇关于什么时候抛出运行时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!