Jun*_*ior 8 php error-handling exception throw
我什么时候应该使用Exception,InvalidArgumentException或UnexpectedValueException?
我不知道他们之间真正的不同,因为我总是使用Exception.
Rob*_*ill 12
不同的异常只会为您提供更多的粒度,并控制您捕获和处理异常的方式.
考虑一个你正在做很多事情的类 - 例如获取输入数据,验证输入数据然后将其保存在某个地方.您可能会认为如果将错误或空参数传递给get()
方法,您可能会抛出一个InvalidArgumentException
.在验证时,如果某些事情与众不同或者不匹配,你可以抛出一个UnexpectedValueException
.如果发生完全意外的事情,你可以抛出标准Exception
.
当你捕获时,这变得很有用,因为你可以用不同的方式处理不同类型的异常.例如:
class Example
{
public function get($requiredVar = '')
{
if (empty($requiredVar)) {
throw new InvalidArgumentException('Required var is empty.');
}
$this->validate($requiredVar);
return $this->process($requiredVar);
}
public function validate($var = '')
{
if (strlen($var) !== 12) {
throw new UnexpectedValueException('Var should be 12 characters long.');
}
return true;
}
public function process($var)
{
// ... do something. Assuming it fails, an Exception is thrown
throw new Exception('Something unexpected happened');
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例类中,当调用它时,您可以使用catch
多种类型的异常,如下所示:
try {
$example = new Example;
$example->get('hello world');
} catch (InvalidArgumentException $e) {
var_dump('You forgot to pass a parameter! Exception: ' . $e->getMessage());
} catch (UnexpectedValueException $e) {
var_dump('The value you passed didn\'t match the schema... Exception: ' . $e->getMessage());
} catch (Exception $e) {
var_dump('Something went wrong... Message: ' . $e->getMessage());
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下你会得到UnexpectedValueException
这样的:string(92) "The value you passed didn't match the schema... Exception: Var should be 12 characters long."
.
还应该注意的是,这些异常类最终都会从Exception扩展,因此如果您没有为InvalidArgumentException
其他人定义特殊处理程序,那么Exception
无论如何它们都会被捕获者捕获.那真的,为什么不使用它们呢?