java 抛运行时异常,什么时候抛出运行时异常?

博客讨论了在编程中何时应该抛出RuntimeException。它指出,当参数无效或者方法调用顺序错误时,应抛出此类异常。文章提供了一个示例代码,涉及洗牌算法,说明在接收到空Deck对象时抛出IllegalArgumentException的合理性,并建议在抛出异常时提供更具体的错误信息。
摘要由CSDN通过智能技术生成

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 cards = d.getDeckOfCards(); // cards is basically Linked List.. cards = new LinkedList()

for(int i=0;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 IllegalArgumentException which I'm most doubtful about. Under what conditions should actually throw a runtime exception? Should we actually throw runtime exception?

Thanks

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值