InvalidArgumentException vs UnexpectedValueException

后端 未结 3 923
我寻月下人不归
我寻月下人不归 2021-02-01 14:06

When should I use InvalidArgumentException and when UnexpectedValueException? They look the same to me.

Note that one extends LogicException and the other one extends Ru

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 14:37

    My understanding is that InvalidArgumentException, being a LogicException, should be used if you check an argument against a fixed list of possible value ranges. For example, checking if user entered data contains only numbers. The program logic can be expected to handle these value ranges.

    UnexpectedValueException, being a RuntimeException (errors that can only be found on runtime / cannot be detected at compile time), would be used for Exceptions that occur outside of foreseeable and specified input ranges (possibly as a last resort after the "logic" checks above).

    The key to answering this question might be the Unexpected... in UnexpectedValueException. Unexpected means there is no handling for this value in the program logic. Invalid, on the other hand, suggests that this value has been handled.

提交回复
热议问题