In PHP, if a value is considered "unknown" (not per se invalid) should this raise a logic or runtime exception?
<?php
function foo($bar) {
// logic
if(!is_string($bar)) {
throw new \InvalidArgumentException('invalid *argument*');
}
if(strlen($bar) < 4) {
throw new \DomainException('invalid *bar*');
}
static $knownBars = array('bar1', 'bar2');
if(!in_array($knownBars)) {
throw new \DomainException('unknown *bar*');
//throw new \UnexpectedValueException('unknown *bar*');
}
// runtime
$bar;
}
The first 2 exceptions are obvious, however the last one remains a bit unclear to me. Both seem to make sense; a logic/domain error as we expect one of a defined data-set, a runtime/unexpected value error as we actually got a unexpected value.
Which one should i throw?
Also what if the logic part is a single setter method and we want to replace the static array (data-set) with a database lookup instead... Is it OK to expect runtime exceptions in logic code due database failure, etc? Or should we move the database lookup to the runtime code and still throw a logic exception if "bar" is considered unknown?
Logic Exceptions are for errors that occur at compile time. Since PHP has no compile time in the sense this is meant, it usually is interpreted as "errors occuring during development", (like when the developer forgot to pass a depedency or something) while Runtime Exceptions are for unforseen errors (usually stemming from User Input) when the code is run.
But frankly, the entire Spl Exception hierarchy is Fubar. So just use what you want or create your own.
Also see https://wiki.php.net/rfc/spl-improvements/exceptions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With