OutOfRangeException vs. OutOfBoundsException

后端 未结 6 1951
我在风中等你
我在风中等你 2020-12-13 18:23

PHP defines two SPL exceptions for invalid keys:

OutOfRangeException: Exception thrown when an illegal index was requested. This represents errors that s

6条回答
  •  星月不相逢
    2020-12-13 19:12

    1. If you get an unexpected index. ie you expect a string but end up with an integer or vice versa. Then you should throw an UnexpectedValueException exception.
    2. If you get a proper type of index but it doesn't exist. Then raise a warning (trigger_error) and proceed on. This is not expected to stop programming flow.
    3. If you have an object that is iterable or supposed to be iterated over a range and it reaches it's limit (ie the end of a file), then you should throw an OutOfBoundsException.
    4. Anything else is a candidate for OutOfRangeException.

    In layman's terms. An OutOfBoundsException is something normal. It's not that serious. It's something that happens often and should be taken care of. it can be used by iterators to keep reading data till there is no more to read. It is a logical error. Made by someone using the code not by someone writing the code.

    An OutOfRangeException is something serious. Someone should look at the source code. Someone should find out what happened. This is important. Theoretically this was never supposed to happen. Call 911. It is a compile time error. Made by the dummy programmer.

    Out of range exceptions are written by programmers to guard against mistakes by other programmers. Or maybe yourself in the future. If you feel like something like that could never happen then use Out Of Range. Use Out of Bounds for something likely to happen.

提交回复
热议问题