OutOfRangeException vs. OutOfBoundsException

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

    The answer to your question is quite elusive to me also. However, here are some things to think about:

    • If an array is passed in when we are expecting a valid array key, we also have InvalidArgumentException because it is not the proper argument type.
    • We could also throw a DomainException because arrays are not in the domain for array keys.
    • In php, you generally can't detect types at compile time because of late static binding. They purposefully delay binding of variables to runtime.

    How I handle this situation:

    • Throw an InvalidArgumentException if a variable is passed in to any function where it the argument is not the correct type. I still do this when working with arrays.
    • Throw an InvalidArgumentException if null was passed in when it shouldn't be. This one really could be a lot of things because null isn't typed. To keep error code checking simple, I simply stick with the invalid argument.
    • Throw OutOfBoundsException when an index is not in the correct range, just as you suggested.
    • Throw BadFunctionCallException if a user-supplied function as a parameter does not have the correct form. If your structure inside is an array, it makes sense that they could pass in a function to modify it, so this comes up occasionally.

    Generally, I can use just these three exceptions to represent all errors that occur outside of special resources (Network and database connections would be special resources). The third one seems to have been cropping up more often, but primarily I've just dealt with the former two.

提交回复
热议问题