While PHP doesn't have a classic "compile time" (or a compiler that do a lot of static checks for that matter) I'd treat "compile time" as "rather static stuff I did wrong when writing the code" and "run time" as "my logic, input or validation was off at some point".
So my suggestion would be to treat it like this:
"Compile Time" / "OutOfRangeException"
: The error can always be fixed in the source code without or with very little logic.
I always take numbers from 1-10 and you put in 11
"Run Time" / "OutOfBoundsException"
: The error is due to wrong use at runtime.
You created me and told me to take values from 1 to 5 then you put in 7. Doesn't compute
or
You request an index that is not there because you didn't put it there like you should
Sample:
I'd expect an SplFixedArray to throw an OutOfBoundsException
because it's size is dynamic and can chance at runtime while I'd expect something like a Calender::getMonthName
to throw and OutOfRangeException
because the number of month are definitely fixed at "compile/write" time.
Array object sample:
Say $array is an object that implements ArrayAccess you could throw an OutOfBoundsException
in these circumstances:
$array['bar'];
$array[7];
As the values are what you could expect for ArrayAccess but it doesn't make sense in the case of an SplFixedArray(5). Alternatives would be DomainException
or maybe RangeException
An OutOfRangeException
in these cases:
$calendar->getMonth(15);
As putting an array or a new class there is definitely some bigger logic flaw in the code that usually results from a simple "oh, i put in the wrong variable" error by a programmer. An (maybe preferable) alternative would be UnexpectedValueException
and good old InvalidArgumentException
.
For cases like:
$array[array()];
$array[new StdClass];
some of the alternative exceptions seem more fitting.
Comparisons with the Java world on which exception to use when are not always applicable as Java Developers have an additions issue to deal with.
Checked/Unchecked exceptions. With many people arguing that everything that isn't a runtime exception has very limited use in Java / should not be used much internally) those names have lost some of their original meaning and intent.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…