What is the best way to catch an IllegalArgumentException

后端 未结 4 2616
星月不相逢
星月不相逢 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:47

    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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-20 12:01

    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.

    0 讨论(0)
  • 2021-02-20 12:04

    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 讨论(0)
提交回复
热议问题