search
HomeBackend DevelopmentPHP TutorialPHP7 error and exception handling example sharing

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.....

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抛出异常

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是在捕获到任何类型的异常后都会运行的一段代码
}
运行结果:exception!end!

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

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的值也可能不同)

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;;

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");//自行触发错误

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();
}

运行结果: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
}

注意实际项目中,在开发环境中我们可以使用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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software