Home Backend Development PHP Tutorial PHP7 error and exception handling example sharing

PHP7 error and exception handling example sharing

Mar 13, 2018 am 09:52 AM
php php7 Example

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles