OutOfRangeException vs. OutOfBoundsException

后端 未结 6 1942
我在风中等你
我在风中等你 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 18:49

    The confusion in this case comes from a couple of factors. First, PHP is in fact compiled into bytecode. There are several execution environments where this compiled form persists in a relatively permanent form on the server. However, the OutOfRangeException/OutOfBoundsException issue is not about that, it's about a categorization error made by the people who documented these specific exception classes.

    Since PHP is dynamically typed, it's often impossible to actually check ranges and even types at compile time. The manual states that OutOfRangeException should be raised at compile time and OutOfBoundsException should apply at runtime, which is an erroneous distinction to make in this context.

    Both manual entries use unclear language of what an illegal index means, but looking at the usage of their parent classes gives some clues: LogicExceptions are extended by classes like DomainException, InvalidArgumentException, and LengthException, whereas Runtime exceptions are things such as UnexpectedValueException, OverflowException and UnderflowException. From this pattern one can infer that OutOfRangeException should probably be applied to illegal key types, and OutOfBoundsException should apply to index values that are of the correct type but are not within the bounds of their container.

    There was some discussion on the PHP dev list about these categorizations being wrong, but the issue goes deeper than that. In practice, both exceptions can only actually be are raised at runtime. You can use the vagaries of the documentation to squeeze out a distinction between invalid key types and invalid index values, but at this point we're talking about a bug in the PHP documentation.

提交回复
热议问题