开发者

What is the best way to catch an IllegalArgumentException

开发者 https://www.devze.com 2022-12-17 15:05 出处:网络
When would be the best use of this type of exception and is it handeled properly if caught in a catch like so?

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)
开发者_运维知识库


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.

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.


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.

If you must catch it you should use

catch(IllegalArgumentException e)


You should stay away from catch (Exception) since that way you'll catch every possible exception. If you really only expect the IllegalArgumentException and handle that case you shouldn't broaden that scope; better add more catch blocks for other types of exceptions, then.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消