When would you throw a DomainException in PHP?

前端 未结 3 608
攒了一身酷
攒了一身酷 2021-02-07 01:13

I was going through the list of predefined Exceptions in PHP and I noticed the DomainException. Anyone know what does DomainException mean? Does it mean failed data model valida

相关标签:
3条回答
  • 2021-02-07 01:38

    The description of RangeException is a bit more helpful:

    Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.

    I think it is applicable to non-arithmetic too, e.g. see this user comment.

    For example, if you expect a value to be in the set {'jpeg', 'png', 'gif', 'bmp'} and you receive something else like 'foo', it's a good candidate for a DomainException (logic) / RangeException (runtime). I'm pretty sure you could think of many other use cases.


    Also, I just found this useful article, which provide more thorough explanations than php.net: How to use built-in SPL exception classes for better error handling

    0 讨论(0)
  • 2021-02-07 01:42

    There's a pretty hilarious discussion here about how no one seems to know what is means:

    http://bugs.php.net/bug.php?id=47097

    From the end of that link:

    Domain means data domain here. That is a DomainException shall be thrown whenever a value does not adhere to a defined valid data domain. Examples:

    • 0 is not in the domain for division.
    • Foo is not in the domain for weekdays.

    The first is different from out of range and alike, but you could use InvalidParameter in case it is actually a parameter to the function that performs the division. If it is a value calculated inside the function prior to executing the division and then a pre-conditon check throws instead of executing the division, then it becomes a DomainException.

    0 讨论(0)
  • 2021-02-07 01:43

    This kind of exception should be used to inform about domain errors in mathematical sense.

    See domain of a function.

    For example, the square root function will only be defined for positive numbers (unless you're using complex numbers...)

    0 讨论(0)
提交回复
热议问题