gpt4 book ai didi

php - OutOfRangeException 与 OutOfBoundsException

转载 作者:IT王子 更新时间:2023-10-29 01:05:54 27 4
gpt4 key购买 nike

PHP 定义了两个 SPL无效键的异常(exception)情况:

OutOfRangeException: Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.

OutOfBoundsException: Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.

由于 PHP 不是一种编译语言,因此编译时和运行时之间的区别似乎很奇怪,因此我很难理解何时使用哪个异常。

目前我的理解是应该扔...
... OutOfRangeException 如果 key 从根本上和固有地格式错误,例如如果数组作为键传递。
... OutOfBoundsException 如果 key 通常没问题,但不在某些边界内,例如如果 100 已通过,但 50 是最大键。

这样理解正确吗?

最佳答案

虽然 PHP 没有经典的“编译时”(或为此做大量静态检查的编译器),但我将“编译时”视为“相当静态的东西,我在编写代码时做错了”和“运行时”作为“我的逻辑、输入或验证在某个时候关闭”。

所以我的建议是这样对待它:

“编译时”/“OutOfRangeException”:该错误始终可以在源代码中修复,无需或只需很少的逻辑。

I always take numbers from 1-10 and you put in 11


"Run Time"/"OutOfBoundsException": 错误是由于运行时错误使用造成的。

You created me and told me to take values from 1 to 5 then you put in 7. Doesn't compute

You request an index that is not there because you didn't put it there like you should


示例:

我希望 SplFixedArray 抛出 OutOfBoundsException,因为它的大小是动态的,并且可能在运行时发生,而我希望像 Calender::getMonthName throw 和 OutOfRangeException 因为月数在“编译/写入”时肯定是固定的。

数组对象示例:

假设 $array 是一个实现 ArrayAccess 的对象,在这些情况下您可以抛出 OutOfBoundsException:

$array['bar'];
$array[7];

因为这些值是您对 ArrayAccess 的期望值,但它在 SplFixedArray(5) 的情况下没有意义。替代方案是 DomainException 或者 RangeException

这些情况下的 OutOfRangeException:

$calendar->getMonth(15);

当放置一个数组或一个新类时,代码中肯定存在一些更大的逻辑缺陷,这通常是由程序员简单的“哦,我输入了错误的变量”错误引起的。一个(可能更可取的)替代方案是 UnexpectedValueException 和旧的 InvalidArgumentException

对于这样的情况:

$array[array()];
$array[new StdClass];

一些替代异常(exception)似乎更合适。

与 Java 世界的比较并不总是适用,因为 Java 开发人员有一个额外的问题需要处理。

已检查/未检查的异常。许多人认为,所有不是运行时异常的东西在 Java 中的使用都非常有限/不应该在内部使用太多)这些名称已经失去了一些原来的含义和意图。

关于php - OutOfRangeException 与 OutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8193798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com