捕获IllegalArgumentException的最佳方法是什么 [英] What is the best way to catch an IllegalArgumentException

查看:188
本文介绍了捕获IllegalArgumentException的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候最好使用这种类型的异常,如果遇到这种情况,它是否能够得到适当处理?

When would be the best use of this type of exception and is it handeled properly if caught in a catch like so?

catch(Exception e)

还是需要明确捕获?

catch(IllegalArgumentException e)


推荐答案

第一个会捕获 ,但是也会有很多其他例外。

It would be caught by the first - but so would a bunch of other exceptions. You shouldn't catch more than you really want to.

如果您真的能抓住它,那么第二个更好。 em>通常,这表明调用代码中存在错误。有时,这是另一种方法的一种情况,这种方法无法验证参数,等等。在理想的世界中,任何时候只要在该位置抛出 IllegalArgumentException ,是调用者在传递值之前对其进行验证的一种方法,或调用将以非例外方式失败的版本(例如,.NET中的 TryParse 模式,在没有 out 参数的情况下,这在Java中更难实现)。并非总是如此,但是每当您收到 IllegalArgumentException 时,都值得检查您是否可以通过在调用方法之前检查值来避免它

The second is better if you really have to catch it... but usually this indicates a bug in the calling code. Sometimes this is a case of another method higher up not validating its arguments, etc. In an ideal world, any time that IllegalArgumentException is thrown there should be a way for the caller to validate the value before passing it in, or call a version which will fail in a non-exceptional way (e.g. the TryParse pattern in .NET, which is admittedly harder in Java without out parameters). That's not always the case, but whenever you get an IllegalArgumentException it's worth checking to see whether you could avoid it by checking the values before calling the method.

这篇关于捕获IllegalArgumentException的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆