Among the changes in PHP7, those that have a greater impact include Exception handling.
More exceptions are handled directly through PHP. Different from the previous PHP5, more exceptions are thrown through Error exceptions.
As a normal extension, Error exceptions will continue to pop up until the corresponding catch
block is matched. If no match is made, the set set_exception_handler()
will be triggered to perform processing. If there is no default exception handler, the exception will be converted to a fatal error and will be treated like a traditional The error is handled.
Since Error does not inherit exceptions in the error hierarchy, code like this catch (Exception $e) { ... }
will not catch the corresponding exception in PHP5. We can use the code catch (Error $e) { ... }
or set_exception_handler()
to handle Error.
Throwable
function add(int $left, int $right) { return $left + $right; }try { echo add('left', 'right'); } catch (Exception $e) { // Handle exception} catch (Error $e) { // Clearly a different type of object // Log error and end gracefully var_dump($e); }
object(TypeError)#1 (7) { ["message":protected]=> string(139) "Argument 1 passed to add() must be of the type integer, string given, called in /Applications/mamp/apache2/htdocs/curl/error.php on line 14" ["string":"Error":private]=> string(0) "" ["code":protected]=> int(0) ["file":protected]=> string(48) "/Applications/mamp/apache2/htdocs/curl/error.php" ["line":protected]=> int(9) ["trace":"Error":private]=> array(1) { [0]=> array(4) { ["file"]=> string(48) "/Applications/mamp/apache2/htdocs/curl/error.php" ["line"]=> int(14) ["function"]=> string(3) "add" ["args"]=> array(2) { [0]=> string(4) "left" [1]=> string(5) "right" } } } ["previous":"Error":private]=> NULL }
function call_method($obj) { $obj->method(); }try { call_method(null); // oops! } catch (EngineException $e) { echo "Exception: {$e->getMessage()}\n"; }//其实上面的例子我在运行过程中,并没有被EngineException捕获异常,经过测试,也是通过Error进行的错误的拦截
The above is the detailed content of Detailed introduction to exception handling code examples in PHP7. For more information, please follow other related articles on the PHP Chinese website!