Home > Backend Development > PHP7 > Error and exception handling in php7

Error and exception handling in php7

齐天大圣
Release: 2023-02-17 17:20:01
Original
2287 people have browsed it

Error

Errors are inevitable in writing programs. How to find, locate and correct errors is a science. Today I will talk to you about the errors and exceptions after php7.

Classification of errors

General errors are divided into syntax errors, runtime errors, and logic errors. Syntax and runtime errors are easy to troubleshoot, but logic errors are not so simple. I have written the comparison operation == as the assignment operation = many times when making judgments. It is difficult for people like me to find it. Generally, as you gain more experience (you step on more pitfalls), it will become easier to find logical errors.

Control error output

It is generally recommended to turn on error output during the development stage to facilitate timely detection of errors. It is recommended to turn off errors during the online stage for the sake of safety and beauty. output.

php provides a parameter display_errors to control the output of errors to the browser and cli. There are two ways to modify it, by modifying the php.ini file or using the ini_set function. The following shows the code that uses ini_set to set up masking error output.

<?php
ini_set(&#39;display_errors&#39;, 0);

echo $a;
echo 0;
date();
echo 1;
Copy after login

The program will output 01 normally, but will not output error information.

Error reporting level

Generally divided into 4 categories

  • parse syntax error

  • errorfatal error

  • warning warning level error

  • notice attention level error

In the php.ini configuration file, there is the option error_reporting, which is used to control what level of errors are output. Common ones include E_ALL, E_WARNING, and E_NOTICE.

You can dynamically control the error level output through the function error_reporting().

# 输出所有级别错误
error_reporting(E_ALL);
# 输出所有级别除了E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
# 输出所有级别除了E_NOTICE和E_WARNING
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING));
Copy after login

The difference between display_errors and error_reporting

display_errors is used to control whether errors are output, while error_reporting is used to control the level of output mistake. Usually they will use

ini_set(&#39;display_errors&#39;, 0); // 关闭错误输出
error_reporting(E_ALL);  // 输出所有级别的错误信息
Copy after login

The above configuration is usually in the online stage, which blocks all error output, but records errors in the PHP error log. The path to the error log is determined by the option error_log.

If error_reporting is set to 0, no errors will be output or error logs will be recorded.

The impact of errors on the program

When the program has syntax errors, the program will not be executed. When there is an error level error, the program will stop executing downward. Notice, and warning level errors will not affect the downward execution of the program.

error_reporting(E_ALL);  // 输出所有级别的错误信息

echo $a;
echo 0;
date();
echo 1;
new a;
echo 2;
Copy after login

This program will output 0 and 1, but not 2.

User-defined error

The trigger_error() function can generate a user-level error. Error levels include E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, etc.

<?php

trigger_error(&#39;这是notice级别错误&#39;, E_USER_NOTICE);
trigger_error(&#39;warning错误&#39;, E_USER_WARNING);
trigger_error(&#39;deprecated&#39;, E_USER_DEPRECATED);
trigger_error(&#39;error错误&#39;, E_USER_ERROR);
Copy after login

Customized error handling

set_error_handler - Set a user-defined error handling function. The function prototype is as follows:

set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] ) : mixed
Copy after login

The The first parameter of the function is a callback function, the prototype is as follows:

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] ) : bool
Copy after login
  • error Error level

  • errstr Error message

  • errfile Send the wrong file

  • errline The line number where the error occurred

The following level errors cannot be defined by user-defined functions To handle: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most E_STRICTs generated in the file where the set_error_handler() function is called.

<?php
 
define(&#39;DEBUG&#39;, false);
 
set_error_handler(&#39;error_handler&#39;);
 
if (DEBUG) {
    ini_set(&#39;display_errors&#39;, &#39;On&#39;);
} else {
    ini_set(&#39;display_errors&#39;, &#39;Off&#39;);
}
 
function error_handler($errLevel, $errInfo, $errFile, $errLine)
{
    echo "ErrorLevel:$errLevel: $errInfo In $errFile ON $errLine" . PHP_EOL;
}
 
echo $a;
Copy after login

Exception

异常和错误时有区别的,错误一般是指我们能控制的问题,比如变量名写错了,或者判断条件写的不错,导致死循环。而异常通常指那些难以控制的、意料外的错误,比如mysql连接不上,文件句柄打开失败等情况。

php的异常也是经典的try catch finally,但和一般的异常处理不一样的是,绝大部分的异常需要自行抛出。抛出异常使用throw关键字完成。php也支持捕获多个异常。

<?php

class MyError extends Exception
{
    public function printErr ()
    {
        echo &#39;出错啦&#39;.PHP_EOL;
    }
}

class YourError extends Exception
{
    public function printErr ()
    {
        echo &#39;errors&#39;.PHP_EOL;
    }
}

try {
    if (mt_rand(0,1)) {
        throw new MyError(&#39;错误&#39;);
    } else {
        throw new YourError(&#39;错误&#39;);
    }


} catch (MyError $e) {
    $e->printErr();
} catch (YourError $e) {
    $e->printErr();
} finally {
    echo &#39;不管有没有异常,我都会被执行&#39;.PHP_EOL;
}
Copy after login
Copy after login

php的异常如果没有捕获,则会报Fatal Error错误,程序不会继续向下执行。

PHP 7 错误处理

PHP 7 改变了大多数错误的报告方式。不同于传统(PHP 5)的错误报告机制,现在大多数错误被作为 Error 异常抛出。 Error 和 Exception 都实现了 Throwable 接口

异常处理

设置默认的异常处理程序,有try/catch捕获的话这个异常函数就不会执行,反之就会执行异常处理函数,而且执行的话,脚本将不会继续执行。

php使用set_exception_handler来设置用户自定义的异常处理函数 ,函数原型如下:

set_exception_handler ( callable $exception_handler ) : callable
Copy after login

回调函数的原型如下:

handler ( Throwable $ex ) : void
Copy after login

下面,我们来写一个异常处理函数

<?php

class MyError extends Exception
{
    public function printErr ()
    {
        echo &#39;出错啦&#39;.PHP_EOL;
    }
}

class YourError extends Exception
{
    public function printErr ()
    {
        echo &#39;errors&#39;.PHP_EOL;
    }
}

try {
    if (mt_rand(0,1)) {
        throw new MyError(&#39;错误&#39;);
    } else {
        throw new YourError(&#39;错误&#39;);
    }


} catch (MyError $e) {
    $e->printErr();
} catch (YourError $e) {
    $e->printErr();
} finally {
    echo &#39;不管有没有异常,我都会被执行&#39;.PHP_EOL;
}
Copy after login
Copy after login

统一处理错误与异常

学完了错误与异常,知道如何去使用自定义错误处理和异常处理,现在我们就可以统一处理错误与异常了。

<?php
 
class Errors
{
    // 处理非致命错误
    static function errorHandle($errLevel, $errInfo, $errFile, $errLine)
    {
        echo &#39;错误:&#39;.PHP_EOL;
        print_r([&#39;file&#39; => $errFile, &#39;level&#39; => $errLevel, &#39;line&#39; => $errLine, &#39;info&#39; => $errInfo]);
    }
 
    // 处理致命错误及异常
    static function exceptionHandle(Throwable $ex)
    {
        echo &#39;异常:&#39;.PHP_EOL;
        print_r([&#39;file&#39; => $ex->getFile(), &#39;level&#39; => $ex->getCode(), &#39;line&#39; => $ex->getLine(), &#39;info&#39; => $ex->getMessage()]);
    }
}
 
set_error_handler([&#39;Errors&#39;, &#39;errorHandle&#39;]);
set_exception_handler([&#39;Errors&#39;, &#39;exceptionHandle&#39;]);
Copy after login

The above is the detailed content of Error and exception handling in php7. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template