Java 捕获 IllegalArgumentException 的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2117541/
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
What is the best way to catch an IllegalArgumentException
提问by ChadNC
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)
Or does it need to be caught explicitly?
还是需要明确捕获?
catch(IllegalArgumentException e)
采纳答案by Jon Skeet
It wouldbe caught by the first - but so would a bunch of other exceptions. You shouldn't catch more than you really want to.
它会被第一个捕获 - 但一堆其他异常也会捕获。你不应该比你真正想要的更多。
The second is better if you really haveto catch it... but usuallythis indicates a bug in the calling code. Sometimes this is a case of another method higher up not validating itsarguments, 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 couldavoid it by checking the values before calling the method.
如果您真的必须抓住它,第二个会更好……但这通常表明调用代码中存在错误。有时这是另一种方法没有验证其参数等的情况。在理想的世界中,任何IllegalArgumentException
抛出的时间都应该有一种方法让调用者在传入值之前验证该值,或者调用一个将以非异常方式失败(例如TryParse
,.NET 中的模式,这在没有out
参数的Java 中无疑更难)。情况并非总是如此,但是每当您得到一个时IllegalArgumentException
,值得检查一下是否可以通过在调用方法之前检查值来避免它。
回答by cjstehno
It really depends on the case at hand, either is correct in itself. Without narrowing down the scope of the question, it's a bit hard to give a "best use" example.
这实际上取决于手头的情况,两者本身都是正确的。在不缩小问题范围的情况下,给出一个“最佳使用”的例子有点困难。
回答by Joey
You should stay away from catch (Exception)
since that way you'll catch everypossible exception. If you really only expectthe IllegalArgumentException
and handle that case you shouldn't broaden that scope; better add more catch blocks for other types of exceptions, then.
你应该远离,catch (Exception)
因为那样你会捕捉到所有可能的异常。如果你真的只希望在IllegalArgumentException
和处理这种情况下,你不应该拓宽范围; 最好为其他类型的异常添加更多的 catch 块,然后。
回答by Arne Deutsch
You should not handle an IllegalArgumentException. It's porpose is to inform the developer, that he have called a method with wrong arguments. Solution is, to call the method with other arguments.
您不应处理 IllegalArgumentException。目的是通知开发人员,他调用了一个带有错误参数的方法。解决方案是,使用其他参数调用该方法。
If you must catch it you should use
如果你必须抓住它,你应该使用
catch(IllegalArgumentException e)