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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months 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)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles