PHP7中异常与错误处理与之前版本对比
先上代码
1 ECHO PHP_VERSION.PHP_EOL; 2 function add (int $left,int $right){ 3 return $left+$right; 4 } 5 try { 6 echo add('left', 'right'); 7 } catch (Exception $e) { 8 // Handle exception 9 } catch (Error $e) { // Clearly a different type of object 10 // Log error and end gracefully 11 var_dump($e->getMessage()); 12 } 13 echo PHP_EOL."helloword".PHP_EOL;
PHP v5.6.27结果
1 5.6.27 2 3 Catchable fatal error: Argument 1 passed to add() must be an instance of int, string given, called in D:\phpStudy\PHPTutorial\WWW\index.php on line 9 and defined in D:\phpStudy\PHPTutorial\WWW\index.php on line 3
PHP v7.0.12结果
1 7.0.12 2 string(127) "Argument 1 passed to add() must be of the type integer, string given, called in D:\phpStudy\PHPTutorial\WWW\index.php on line 9" 3 helloword
区别
在于后者可以捕获fatal error,并且可以正常输出helloword.
链接:https://www.php.cn/topic/php7/436271.html