


Detailed explanation of errors and exceptions in PHP and related knowledge
PHP error level
Parse error
> Fatal Error
> Waning
> Notice
> Deprecated
- ##Deprecated The lowest level error (not recommended, not Suggestion)
It will appear when using some expired functions, and the program continues to execute - Notice notification level error
Use some undefined It will appear when variables, constants or array keys are not quoted, and the program will continue to execute - Waning warning level error
There is a problem with the program and it needs to be modified Code! ! ! The program continues to execute - Fatal Error Error level error
The program reports an error directly and the code needs to be modified! ! ! To interrupt program execution, you can use the register_shutdown_function() function to trigger a function before the program terminates - Parse error Syntax parsing error
An error is reported during the syntax check phase and needs to be modified Code! ! ! Interrupting program execution, nothing can be done except modifying the ini file and writing error messages to the log - E_USER_related errors
User-defined Error, the user manually throws the error and performs customized error handling
PHP error related functions
ini_set('display_errors', 0);
//Turn off error output (development environment is on, production environment is off)
error_reporting(E_ALL&~E_NOTICE);
//Set the error reporting level
ini_set('error_reporting',0);
//Set the error reporting level
PHP error configuration
- In addition to setting in the script, you can also set it in php.ini Configure in the configuration file
error_reporting = E_ALL&~E_NOTICE;
//Set the error reporting level
display_errors = 1;
//Open the development environment and close the production environment
PHP exception
- ##PHP exceptions are a newly added feature. Different from JAVA/C# exceptions, PHP exceptions need to be thrown manually
- throw new Exception
instead of being automatically thrown by the system
The difference between PHP errors and exceptions, they are two - different concepts
, but they have something in common:
If the exception is not caught and handled, the program will terminate , and report a Fatal Error. When you see this, everyone will think that the exception is a kind of error. This is an illusion, but it can be understood this way. However, the program can continue to execute after the exception is caught, but the program must terminate after the real Fatal Error occurs. Exceptions can be handled using - try{}catch( ){}
to capture the capture. After the capture, subsequent code can continue to execute; and errors cannot be captured using
try{}catch(){}
If an exception is thrown, it must be caught, otherwise the program will terminate execution.
PHP exception and error throwing
- Exception throwing:
- throw new Exception('Some Error Message');
- trigger_error()
- trigger_error()
Triggered errors will not be captured by
try-catch
exception catching statements
##set_error_handler()
-
Deprecatedcan only handle
,
, Waning
These three levels of errors, and after processing, the script will continue to execute the line after the error
This method is the last callback function before the end of the script, so it will be called whether it is die()/error (exception)/or the script ends normally
PHP exception handling
set_exception_handler()
-
Set the default exception handler. If there is a try/catch capture, this function will not be executed. Otherwise, it will be executed. And if it is executed, the script will not continue to execute the next line of code where the exception occurs, and the program will terminate immediately
- Notes
-
function nameset_exception_handler(“myException”) not only accepts
,
can also be accepted (public static methods and public non-static methods are acceptable), but they need to be in array form Pass, the first value of the array is "class name", and the second parameter is "method name", as shown in the following code: <?php
class App{
function myException($exception) {
echo "<b>Exception:</b> " , $exception->getMessage();
}
}
set_exception_handler(array('App','myException'));
throw new Exception('Uncaught Exception occurred');
?>
Exception caused by user behavior
- 1. Failure to pass the validator
2、没查询到结果
3、需要向用户返回具体信息
4、不需要记录日志
5、可作为异常或者不作为异常,根据需求和个人情况而定
由于服务器自身导致出现异常
1、代码出错
2、调用第三方接口错误
3、不需要向用户返回具体信息
4、需要记录日志
在程序中PHP异常的自动抛出
由于PHP异常是后面版本新增的特性,设计上与JAVA/C#的异常不一样,JAVA的异常大部分是系统自动抛出,而
PHP异常不是系统自动抛出
,需要手动抛出
,导致PHP异常在程序中的作用减半
(异常就是意料之外的事情,根本我们意料不到的,如果用手动抛出,证明已经预先预料到了,那异常的意义就变味了)在PHP中
异常是手动抛出的
,而错误是系统自动抛出的
(也可手动抛)我们需要把
异常做成系统自动抛出接
(例如JAVA)就必须借助错误
(这三种错误Deprecated
、Notice
、Waning
,其他的错误不行,因为会终止程序运行)
<?php set_error_handler('error_handler'); function error_handler($errno, $errstr, $errfile, $errline) { throw new Exception($errstr); } try { $num = 100 / 0; } catch(Exception $e) { echo $e -> getMessage() . '<br/>'; } echo "end"; ?>
执行结果:
Division by zero end
PHP7 异常处理的大变化
一段TP5源代码引出
PHP7异常
的变化明明set_exception_handler()函数只可以捕获
Exception类或派生类的对象
,为何还需要捕获的对象做判断呢?结果引出了PHP7
的变化,请看下面分析前面已经讲过异常是需要
手动抛出
,及时上面所说的方法最多也是把Deprecated
、Notice
、Waning
这3类错误封装成系统自动抛出的异常,但致命错误仍然还是无法封装成系统自动抛出的异常,因为致命错误(Fatel Error)仍然无法捕获在PHP7之前,
Deprecated
、Notice
、Waning
这类错误是可以捕获的(使用set_error_handler()函数),而Fatel Error
无法捕获的在PHP7之后,出现了一个异常与错误通用的接口Throwable,Exception类与Error类都实现了该接口,导致
Error类或Error类的派生类的错误对象
(大部分Fatel Error,而之前三类错误不变)也可以像Exception一样被捕获(2种捕获方法:1、try/catch 2、set_exception_handler())示例代码
try{ go();//该函数未定义 }catch(Exception $e){ //捕获异常 }catch(Error $er){ //捕获错误 }
相关教程推荐:《PHP教程》
The above is the detailed content of Detailed explanation of errors and exceptions in PHP and related knowledge. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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

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,

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

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

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