Table of Contents
Exception refers to a situation that does not meet expectations and is different from the normal process during program operation.
is a problem that belongs to the PHP program itself. It is usually caused by illegal syntax and environmental problems, which makes the compiler fail to pass the check or even fail to run.
In the previous php5. Throw the error in try-catch
functions to host errors Handler, you can customize the error handling process.
For uncaught exception handling
Function: Register a function that will be executed when PHP terminates
Home Backend Development PHP7 Detailed explanation of exception and error handling in php7

Detailed explanation of exception and error handling in php7

Mar 30, 2021 am 10:38 AM

Detailed explanation of exception and error handling in php7

First of all, let me state that the author’s PHP version is 7.2

    • ##Overview of exceptions and errors
        • What is exception?
        • What is an error?
        • Exception handling
    • Level of error
    • Custom error handler
        • set_error_handler()
        • set_exception_handler()
        • register_shutdown_function()
        • Framework error handling

Recommended (free): PHP7

##Overview of exceptions and errors

What is exception?

Exception refers to a situation that does not meet expectations and is different from the normal process during program operation.

For example, if you connect to the database and all the parameters are written, but you find that the link cannot go up, this is not as expected.

Can be captured by try-catch

What is an error?

is a problem that belongs to the PHP program itself. It is usually caused by illegal syntax and environmental problems, which makes the compiler fail to pass the check or even fail to run.

The warming and notices we usually encounter are all errors, but they are of different levels.


For example:

TypeError (type error) The function parameter type I specified is inconsistent with the parameter passed in
  • ArithmeticError (arithmetic error)
  • ParseError (parsing error) In the loaded file, there is a syntax error in include "demo.php" or eval(); causing parsing failure
  • AssertionError (Assertion error) This error is generated when assert takes effect.
  • pisionByZeroError (the denominator is zero) During the operation, such as division, the denominator is 0
  • Except for these situations, the rest are all exceptions

Exception handling

In the previous php5. Throw the error in try-catch

So if you want to catch an exception in the future, and you don’t know whether the exception is an Error or an Exception, you can throw it like this

try{
    ……
}catch(Throwable $e){
    ……
}
Copy after login

Error levels

Errors in php also have levels

Parse error

>

Fatal Error > Waning > Notice >Deprecated

Deprecated 最低级别的错误(不推荐,不建议)
使用一些过期函数的时候会出现,程序继续执行

Notice 通知级别的错误
使用一些未定义变量、常量或者数组key没有加引号的时候会出现,程序继续执行
        E_NOTICE      // 运行时通知。表示脚本遇到可能会表现为错误的情况.
        E_USER_NOTICE // 用户产生的通知信息。Waning 警告级别的错误
程序出问题了,需要修改代码!!!程序继续执行
        E_WARNING         // 运行时警告 (非致命错误)。
        E_CORE_WARNING    // PHP初始化启动过程中发生的警告 (非致命错误) 。
        E_COMPILE_WARNING // 编译警告
        E_USER_WARNING    // 用户产生的警告信息Fatal Error 错误级别的错误
程序直接报错,需要修改代码!!!中断程序执行,可使用register_shutdown_function()函数在程序终止前触发一个函数
        E_ERROR         // 致命的运行错误,错误无法恢复,暂停执行脚本
        E_CORE_ERROR    // PHP启动时初始化过程中的致命错误
        E_COMPILE_ERROR // 编译时致命性错,就像由Zend脚本引擎生成了一个E_ERROR
        E_USER_ERROR    // 自定义错误消息。像用PHP函数trigger_error(错误类型设置为:E_USER_ERROR)Parse error 语法解析错误
语法检查阶段报错,需要修改代码!!!中断程序执行,除了修改ini文件,将错误信息写到日志中,什么也做不了
        E_PARSE  //编译时的语法解析错误
Copy after login
Custom error handler

Sometimes , the error handler that comes with PHP cannot fully meet our needs. Most of the time, we need to manually rewrite exception handling.

php provides us with three functions to help us handle them, namely

set_error_handler()

functions to host errors Handler, you can customize the error handling process.

    If an error occurs in the code before this function, our custom processing function will not be called because it has not been registered yet
  • After setting this function, error_reporting() will be invalid
  • The following level errors cannot be handled by user-defined functions: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING. This function can only capture some of our Warning and Note level errors
  • set_exception_handler()

For uncaught exception handling

  • register_shutdown_function()

Function: Register a function that will be executed when PHP terminates

    Capture PHP errors: Fatal Error, Parse Error, etc. This method is the last function called before the PHP script execution ends, such as script errors, die(), exit, exception, and normal end will all be called.
  • If used for error handling, you need to cooperate with
  • error_get_last()
  • It can get the last error that occurred.
  • <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>举例 register_shutdown_function(&amp;#39;shutdown&amp;#39;);function shutdown(){ if ($error = error_get_last()) { var_dump($error); } }$name //没写 ; 号</pre><div class="contentsignin">Copy after login</div></div>Execution resultParse error: syntax error, unexpected ';' in /app/swoole/errorDemo.php on line 34</p> <p> <br> Emmmmm This is not nonsense ? Is it clearly not executed? <code>In fact, the reason is that before the program is executed, our PHP will first check the syntax problems of our program. If there are no problems, we can execute our program.

    Our above code did not pass our syntax check, so an error was reported directly.

    Then the question comes? When we are in the framework, why do the frameworks always report errors to us?

    Error handling of the framework

    In the framework, its code is loaded through an entry file. When our PHP detects syntax errors, we only check our index.php. If it requires, it will not be detected. When our code makes an error, it is an error detected in run-time, so the corresponding error in our framework can be

    The above is the detailed content of Detailed explanation of exception and error handling in php7. 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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to Use Sessions Effectively in PHP 7? How to Use Sessions Effectively in PHP 7? Mar 10, 2025 pm 06:20 PM

This article details effective PHP 7 session management, covering core functionalities like session_start(), $_SESSION, session_destroy(), and secure cookie handling. It emphasizes security best practices including HTTPS, session ID regeneration, s

How to Monitor PHP 7 Performance with Tools like New Relic? How to Monitor PHP 7 Performance with Tools like New Relic? Mar 10, 2025 pm 06:28 PM

This article explains how to monitor PHP 7 application performance using New Relic. It details New Relic's setup, key performance indicators (KPIs) like Apdex score and response time, bottleneck identification via transaction traces and error track

How to Upgrade from PHP 5.6 to PHP 7? How to Upgrade from PHP 5.6 to PHP 7? Mar 10, 2025 pm 06:29 PM

This article details upgrading PHP 5.6 to PHP 7, emphasizing crucial steps like backing up, checking server compatibility, and choosing an upgrade method (package manager, compiling, control panel, or web server configuration). It addresses potentia

How to Autoload Classes in PHP 7? How to Autoload Classes in PHP 7? Mar 10, 2025 pm 06:20 PM

This article explains PHP 7's autoloading, using spl_autoload_register() to load classes on demand. It details best practices like namespace-based autoloading and caching for performance optimization, addresses common issues (e.g., class not found

How to Use Git for Version Control in PHP 7 Projects? How to Use Git for Version Control in PHP 7 Projects? Mar 10, 2025 pm 06:27 PM

This article guides PHP 7 developers on using Git for version control. It covers initialization, staging, committing, ignoring files, remote repositories, branching, merging, conflict resolution, and essential Git commands. Best practices for effic

How to Deploy a PHP 7 Application to a Web Server? How to Deploy a PHP 7 Application to a Web Server? Mar 10, 2025 pm 06:28 PM

This article details deploying PHP 7 applications, covering methods (FTP, SSH, deployment tools), server configuration (Apache/Nginx, PHP-FPM), database setup, and crucial security considerations. It highlights common challenges like server compatib

How to Use Xdebug for Debugging PHP 7 Code? How to Use Xdebug for Debugging PHP 7 Code? Mar 10, 2025 pm 06:26 PM

This article explains how to use Xdebug for debugging PHP 7 code. It covers Xdebug configuration (installation, php.ini settings, IDE setup), breakpoint usage (conditional, function, remote), and troubleshooting connection issues. Effective debuggi

How to Include and Require Files in PHP 7? How to Include and Require Files in PHP 7? Mar 10, 2025 pm 02:52 PM

This article explains PHP 7's include, include_once, require, and require_once file inclusion methods. It details their differences in error handling (warnings vs. fatal errors) and multiple inclusion prevention. Best practices for file organizatio

See all articles