Home  >  Article  >  Backend Development  >  How to catch errors in php

How to catch errors in php

藏色散人
藏色散人Original
2020-07-10 10:24:572871browse

How to catch errors in php: 1. Use the "try catch" statement to catch errors; 2. Use the "set_exception_handler" method to catch errors, which is used to set user-defined exception handling functions.

How to catch errors in php

PHP error capture processing

The general method used to capture errors is:

try{
  ...
}catch(Exception $e){
  echo $e->getMessage();
}

or

set_exception_handler(function ($exception) {
  echo $exception->getMessage();
});

Example:

<?php
function test(){
    throw new Exception(&#39;参数错误&#39;);
}
try{
    //如果catch没有捕获到,才会执行到这里
    set_exception_handler(function ($exception) {
        echo $exception;//exception &#39;Exception&#39; with message &#39;参数错误&#39; in /www/web/...(一堆信息)
        echo &#39;<br>&#39;;
        echo $exception->getMessage();//参数错误
    });
    test();
}catch(Exception $e){
    echo $e->getMessage();//参数错误
}

set_exception_handler - Set a user-defined exception handling function for exceptions that are not caught with try/catch blocks.

For more related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to catch errors in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn