Home Backend Development PHP7 Analyze errors and exceptions in PHP7 together

Analyze errors and exceptions in PHP7 together

Oct 14, 2021 pm 04:44 PM
mysql php

Recommended: "PHP7 Tutorial"

The reason why PHP language is simple One of them is PHP's error handling mechanism. As the PHP language becomes more and more modern, exceptions also appear. This blog post simply talks about errors and exceptions to facilitate the system's understanding. In addition, for any language, exceptions There are commonalities, so it is essential to learn a language and understand the exception mechanism.

What is an error
When the PHP language encounters an abnormal situation (such as database connection (or function parameters are passed incorrectly), some errors will be reported. Errors can be divided into many types. Except for E_ERROR and E_CORE_ERROR errors, other errors will not terminate the program.
The reason why PHP makes people feel simple is that The program will not frequently report errors, giving people the illusion of smooth and convenient writing.
It is precisely for this reason that the rigor and accuracy of PHP programs are much worse. For example, when the mysql_fetch_array query encounters a network error and returns FALSE ( The program does not terminate running), if the calling program thinks that the query does not have matching data, the program is essentially wrong.
We can choose what type of errors to report through the error_reporting instruction in php.ini or dynamically calling the error_reporting() function. The display_errors command can control whether errors are output online. The error_log command can control the error output to the log.

How to use errors correctly
Whether it is a system function or a custom one If a function encounters an error internally, how does it notify the caller? It is usually indicated by the function returning TRUE or FALSE. This processing method has several disadvantages:
● The caller only knows that an error has occurred, but the returned There is too little error information and lack of description of the error type
● Program processing logic and error handling are mixed together, and the generated code will be very unclear.
A little trick: the error_get_last() function will return the most recent error. The specific reason.

Best practice:
● set_error_handler() function to host all errors
● The trigger_error() function can trigger custom errors and can be used Replace the return statement in the function
● Output all errors to the log and define the error type
● Display errors to users, such as returning errors to users in a more friendly way
● Production The display_errors command should be turned off in the environment and turned on in the development environment.
The old PHP framework Codeigniter can learn from the way it handles errors

`function _error_handler($severity, $message, $filepath, $line)
{
    $is_error = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $severity) === $severity);
    //输出500错误HTTP状态码
    if ($is_error) {
        set_status_header(500);
    }
    //对于不需要处理的错误则直接中断
    if (($severity & error_reporting()) !== $severity) {
        return;
    }
    //将所有的错误记录到日志中
    $_error =& load_class('Exceptions', 'core');
    $_error->log_exception($severity, $message, $filepath, $line);
    //友好的输出所有错误
    if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
        $_error->show_php_error($severity, $message, $filepath, $line);
    }
    //假如致命错误则直接退出
    if ($is_error) {
        exit(1);   
    }
}
set_error_handler('_error_handler');`
Copy after login

What is an exception
Exception is also an error , it has the following characteristics:
● Exceptions can be customized, SPL provides many types of exceptions, and you can also extend it
● The most common action for exceptions is to capture, so that developers can customize the exceptions based on specific errors. Carry out subsequent processing. For example, you can return a friendly prompt to the user based on the context of the exception. Or continue to throw an exception and let the upstream program handle it. If the exception is still not caught, the program will terminate directly.
● Exceptions in addition The first action is to throw. If you write business logic through functions and encounter unexpected situations, you can directly throw an exception.
● Exceptions can be caught by the code layer by layer. If the outermost program has not caught it yet, The code will terminate running directly
●If the exception in PHP cannot be caught, it will be written to the system error log as a fatal error
Illustrated through intuitive code:

`function inverse($x)
{
    if ($x < 10) {
        throw new Exception(&#39;x<10&#39;);
    } elseif ($x >= 10 and $x < 100) {
        throw new LogicException(&#39;x>=10 and x<100&#39;);
    }
    return $x;
}
try {
    echo inverse(2)."\n";
} catch (LogicException $e) {
    echo &#39;Caught LogicException: &#39;, $e->getMessage(), "\n";
} catch (Exception $e) {
    echo 'Caught Exception: ', $e->getMessage(), "\n";
    throw $e;
}`
Copy after login

Exception Best practices
● Exceptions can make the code clearer, allowing developers to focus on writing business logic.
● Building extensible exceptions is very technical. Isn’t SPL exception not enough? Is it?
● Catching exceptions should only capture exceptions that can be handled by this layer, and let upstream code handle exceptions that cannot be handled.

Exceptions in PHP7
PHP7 It is encouraged to use exceptions to replace errors, but it is impossible to overturn the error handling mechanism all at once. Compatibility is required, so the transition can only be made slowly.
But exceptions can be used uniformly through workarounds
● Error exception
PHP An Error exception is defined in. Note that this exception and Exception are juxtaposed.
When strict mode is turned on, many errors in PHP7 are thrown by Error exceptions. In this way, exceptions can be used uniformly.

`declare (strict_types = 1);
function add(int $a, int $b)
{
    return $a + $b;
}
try {
    echo add("3", "4");
}
catch (TypeError $e) { //TypeError继承自Error
    echo $e->getMessage();
}`
Copy after login

● ErrorException
ErrorException inherits from Exception.
We can convert all errors into ErrorException through the set_error_handler() function. In this way, we can use exceptions happily.
The above is a systematic understanding The details of errors and exceptions in PHP, I hope it will be helpful to you.
Read the original text: Systematic understanding of errors and exceptions in PHP

The above is the detailed content of Analyze errors and exceptions in PHP7 together. 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

Video Face Swap

Video Face Swap

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

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 and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 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.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 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.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

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

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

See all articles