- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
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];
与 Java 世界的比较并不总是适用,因为 Java 开发人员有一个额外的问题需要处理。
已检查/未检查的异常。许多人认为,所有不是运行时异常的东西在 Java 中的使用都非常有限/不应该在内部使用太多)这些名称已经失去了一些原来的含义和意图。
关于php - OutOfRangeException 与 OutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8193798/
有谁知道为什么这段代码会返回超出范围的异常? 例如,如果 leastAbstractions列表实例有 count == 10 , 循环将执行 11次以 i = 10 结束并返回此异常。 for (
PHP 定义了两个 SPL无效键的异常(exception)情况: OutOfRangeException: Exception thrown when an illegal index was re
所以我一直在努力建立一个 SQL 单词数据库,据我从调试日志中可以看出,它实际上确实正确地加载和设置了。但是,当我尝试查询它时,无论它是在设置过程中还是已经完成,我的程序都因为异常而被强制关闭。对日志
我正在尝试使用 Apache Commons Math 库以及 PolynomialSplineFunction 和 LinearInterpolator 函数来实现外推函数。 public dou
我有两个使用 SemaphoreSlim 和字符串数组“Contents”的循环 一个foreach循环: var allTasks = new List(); var
我正在搞乱 Accord.NET 中的不同深度学习算法。我决定用我手边的光谱数据来做这件事。我使用 Accord 的统计工具箱对数据进行 PCA 转换,使其减少到 10 个数据点。然后严格按照教程进行
我是一名优秀的程序员,十分优秀!