InvalidArgumentException 与 UnexpectedValueException

2024-05-27

我应该什么时候使用无效参数异常 http://www.php.net/manual/en/class.invalidargumentexception.php什么时候意外值异常 http://www.php.net/manual/en/class.unexpectedvalueexception.php?它们在我看来是一样的。

Note http://php.net/manual/en/spl.exceptions.php#spl.exceptions.tree一个扩展了 LogicException,另一个扩展了 RuntimeException,因此在我看来,差异不应该如此微妙。


仔细查看手册页上的描述:

无效参数异常 https://www.php.net/manual/en/class.invalidargumentexception.php

如果抛出异常参数不是预期的类型.

(The description was Exception thrown if an argument does not match with the expected value. until mid-2014 https://web.archive.org/web/20140119224439/https://www.php.net/invalidargumentexception, but was changed when PHP 5.6 got introduced https://web.archive.org/web/20140606205440/https://www.php.net:80/invalidargumentexception)

意外值异常 https://www.php.net/manual/en/class.unexpectedvalueexception.php

如果抛出异常某个值与一组值不匹配。通常,当一个函数调用另一个函数并期望返回值是某种类型或值[](不包括算术或缓冲区相关错误)时,就会发生这种情况。

由此,我们可以得出结论InvalidArgumentException旨在检查参数类型传递给函数,同时UnexpectedValueException旨在验证值与有效值集,可能在函数的内部计算期间(例如从其他函数返回的值)。

请注意,检查参数的值在这里是一种灰色区域;可以说,自从InvalidArgumentException extends LogicException,它应该只处理以下情况should lead directly to a fix in your code. https://www.php.net/manual/en/class.logicexception.php#Introduction因为在输入值超出范围的情况下抛出异常是完全可以预料的runtime行为,这使得UnexpectedValueException(这延伸了RuntimeException)作为这种情况下的唯一候选人。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

InvalidArgumentException 与 UnexpectedValueException 的相关文章

随机推荐