PHP7 error and exception handling example sharing

小云云
Release: 2023-03-21 09:24:02
Original
2443 people have browsed it

Similarities and Differences between Errors and Exceptions

The concepts of "error" and "exception" are very similar and can be easily confused. Both "error" and "exception" indicate that there is a problem with the project and will provide relevant information. , and both have error types. However, the "exception mechanism" appeared after the "error mechanism", and "exception" is the shortcoming of avoiding "errors". The more important point is that the "error" information is not rich. The most common function description we have seen is: return *** when successful, and return FALSE when error occurs. However, there may be many reasons for a function error, and the types of errors There are many more. A simple FALSE cannot tell the caller the specific error message.

In PHP, the code's own exception (usually caused by the environment or illegal syntax) becomes an error and will appear during operation. Logical errors are called exceptions. Errors cannot be handled by code, but exceptions can be handled by try/catch.

Exception

Exception is an object of the Exception class. When encountering It is thrown when a situation cannot be repaired. When a problem occurs, exceptions are used to take the initiative and delegate responsibilities. Exceptions can also be used for defense, predicting potential problems and mitigating their impact.

Exception object has two main properties: one is the message and the other is the numeric code. We can obtain these two properties using getCode() and getMessage() respectively. As follows:

<?php 
$exception = new Exception("figthing!!!",100);
$code = $exception->getCode();//100
$message = $exception->getMessage();//fight.....
Copy after login

Throw exception

When an exception is thrown, the code will stop executing immediately, and subsequent code will not continue to execute. PHP will try to find a matching "catch" code block. If an exception is not caught and is not handled accordingly using set_exception_handler(), PHP will generate a serious error and output an Uncaught Exception... message.

throw new Exception("this is a exception");//使用throw抛出异常
Copy after login

Catch exceptions

We should catch thrown exceptions and handle them in an elegant way. The way to intercept and handle exceptions is to put the code that may throw exceptions into try/catch blocks. And if multiple catches are used to intercept multiple exceptions, only one of them will be run. If PHP does not find a suitable catch block, the exception will bubble up until the PHP script terminates due to a fatal error. As follows:

try {
	throw new Exception("Error Processing Request");
	$pdo = new PDO("mysql://host=wrong_host;dbname=wrong_name");
} catch (PDOException $e) {
	echo "pdo error!";
} catch(Exception $e){
	echo "exception!";
}finally{
    echo "end!";//finally是在捕获到任何类型的异常后都会运行的一段代码
}
Copy after login
运行结果:exception!end!
Copy after login

Exception handler

So how should we catch every exception that may be thrown? PHP allows us to register a global exception handler to catch all uncaught exceptions. Exception handlers are registered using the set_exception_handler() function (an anonymous function is used here).

set_exception_handler(function (Exception $e)
{
	echo "我自己定义的异常处理".$e->getMessage();
});
throw new Exception("this is a exception");
//运行结果:我自己定义的异常处理this is a exception
Copy after login

Error

In addition to exceptions, PHP also provides functions for reporting errors. PHP can trigger different types of errors, such as fatal errors, runtime errors, compile-time errors, startup errors, and user-triggered errors. The error reporting method can be set in php.ini (no further explanation here)

The following are some error reporting levels:

值          常量                     说明1           E_ERROR             报告导致脚本终止运行的致命错误2   
        E_WARNING           报告运行时的警告类错误(脚本不会终止运行)4           E_PARSE        
             报告编译时的语法解析错误8           E_NOTICE            报告通知类错误,脚本可能会产生错误32767 
                  E_ALL               报告所有的可能出现的错误(不同的PHP版本,常量E_ALL的值也可能不同)
Copy after login

In any case, the following rules must be followed:

  • Be sure to let PHP report errors

  • Display errors in the development environment

  • In the production environment Errors cannot be displayed in

  • Errors must be logged in both development and production environments

Error handlers

and exceptions Like handlers, we can also use set_error_handler() to register a global error handler and use our own logic to intercept and handle PHP errors. We need to call the die() or exit() function in the error handler. If not called, the PHP script will continue execution from the point where the error occurred. As follows:

set_error_handler(function ($errno,$errstr,$errfile,$errline)//常用的四个参数
{
	echo "错误等级:".$errno."<br>错误信息:".$errstr."<br>错误的文件名:".$errfile."<br>错误的行号:".$errline;
	exit();
});
trigger_error("this is a error");//自行触发的错误
echo &#39;正常&#39;;
Copy after login

Running results:
Error level: 1024
Error message: this is a error
Error file name:/Users/toby/Desktop/www/Exception.php
Wrong line number: 33

There is also a related function register_shutdown_function()---a function that will be executed when PHP is terminated. (If you are interested, you can check it yourself)

Convert errors to exceptions

We can convert PHP errors into exceptions (not all errors can be converted, only the php.ini file can be converted Errors set by the error_reporting directive), handle errors using the existing process for handling exceptions. Here we use the set_error_handler() function to host the error information to ErrorException (which is a subclass of Exception), and then hand it over to the existing exception handling system for processing. As follows:

set_exception_handler(function (Exception $e)
{
	echo "我自己定义的异常处理".$e->getMessage();
});
set_error_handler(function ($errno, $errstr, $errfile, $errline )
{
	throw new ErrorException($errstr, 0, $errno, $errfile, $errline);//转换为异常
});
trigger_error("this is a error");//自行触发错误
Copy after login

Running results: My own defined exception handling this is a error

PHP7 error exception handling

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

这种 Error 异常可以像 Exception 异常一样被第一个匹配的 try / catch 块所捕获。如果没有匹配的 catch 块,则调用异常处理函数(事先通过 set_exception_handler() 注册)进行处理。 如果尚未注册异常处理函数,则按照传统方式处理:被报告为一个致命错误(Fatal Error)。

Error 类并非继承自 Exception 类,所以不能用 catch (Exception $e) { ... } 来捕获 Error。你可以用 catch (Error $e) { ... },或者通过注册异常处理函数( set_exception_handler())来捕获 Error。

$a=1;
try {
$a->abc();//未定义此对象
} catch (Exception $e) {
	echo "error";
} catch (Error $e) {
	echo $e->getCode();
}
Copy after login

运行结果:0

PHP7 中出现了 Throwable 接口,该接口由 Error 和 Exception 实现,用户不能直接实现 Throwable 接口,而只能通过继承 Exception 来实现接口

try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}
Copy after login

注意实际项目中,在开发环境中我们可以使用Whoops组件,在生产环境中我们可以使用Monolog组件。

相关推荐:

PHP错误处理方法实例

php错误处理和日志记录

PHP异常处理和错误处理方法分享

The above is the detailed content of PHP7 error and exception handling example sharing. 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