search
HomeBackend DevelopmentPHP TutorialDetailed explanation of errors and exceptions in PHP and related knowledge

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

  • Error throw:
  • trigger_error()

  • trigger_error()

    Triggered errors will not be captured by try-catch exception catching statements

##PHP error handling

##set_error_handler()
  • can only handle

    Deprecated
  • ,
Notice

, Waning These three levels of errors, and after processing, the script will continue to execute the line after the error

register_shutdown_function()
  • 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

set_exception_handler()
    Notes
  • set_exception_handler(“myException”) not only accepts

    function name
  • ,
class methods

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(&#39;App&#39;,&#39;myException&#39;));
 
throw new Exception(&#39;Uncaught Exception occurred&#39;);
?>
PHP exception classification

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)就必须借助错误(这三种错误DeprecatedNoticeWaning,其他的错误不行,因为会终止程序运行)

<?php

    set_error_handler(&#39;error_handler&#39;);

    function error_handler($errno, $errstr, $errfile, $errline) {
        throw new Exception($errstr);
    }

    try {
        $num = 100 / 0;
    } catch(Exception $e) {
        echo $e -> getMessage() . &#39;<br/>&#39;;
    }

    echo "end";
?>

执行结果:

Division by zero
end

PHP7 异常处理的大变化

  • 一段TP5源代码引出PHP7异常的变化

    Detailed explanation of errors and exceptions in PHP and related knowledge

    明明set_exception_handler()函数只可以捕获Exception类或派生类的对象,为何还需要捕获的对象做判断呢?结果引出了PHP7的变化,请看下面分析

  • 前面已经讲过异常是需要手动抛出,及时上面所说的方法最多也是把DeprecatedNoticeWaning这3类错误封装成系统自动抛出的异常,但致命错误仍然还是无法封装成系统自动抛出的异常,因为致命错误(Fatel Error)仍然无法捕获

  • 在PHP7之前,DeprecatedNoticeWaning这类错误是可以捕获的(使用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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.