gex*_*ide 6 php exception nullpointerexception
当我尝试访问null对象上的成员或方法时,有没有办法告诉PHP抛出异常?
例如:
$x = null;
$x->foo = 5; // Null field access
$x->bar(); // Null method call
Run Code Online (Sandbox Code Playgroud)
现在,我只得到以下错误,这些错误不适合处理:
PHP Notice: Trying to get property of non-object in ...
PHP Warning: Creating default object from empty value in ...
PHP Fatal error: Call to undefined method stdClass::bar() in ...
Run Code Online (Sandbox Code Playgroud)
我想要抛出一个特定的异常.这可能吗?
小智 6
从 PHP7 开始,您可以捕获致命错误,示例如下:
$x = null;
try {
$x->method();
} catch (\Throwable $e) {
throw new \Exception('$x is null');
}
Run Code Online (Sandbox Code Playgroud)
您可以使用set_error_handler()将警告转换为异常,因此每当发生警告时,它都会生成一个异常,您可以在 try-catch 块中捕获该异常。
致命错误不能转变为异常,它们是为 PHP 尽快停止而设计的。但是,我们可以通过使用register_shutdown_function()进行一些最后一刻的处理来优雅地处理致命错误
<?php
//Gracefully handle fatal errors
register_shutdown_function(function(){
$error = error_get_last();
if( $error !== NULL) {
echo 'Fatal Error';
}
});
//Turn errors into exceptions
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try{
$x = null;
$x->foo = 5; // Null field access
$x->bar(); // Null method call
}catch(Exception $ex){
echo "Caught exception";
}
Run Code Online (Sandbox Code Playgroud)