What is the best way to catch an IllegalArgumentException

后端 未结 4 2550
星月不相逢
星月不相逢 2021-02-20 11:02

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 ne

4条回答
  •  别那么骄傲
    2021-02-20 11:57

    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.

提交回复
热议问题