search
HomeBackend DevelopmentPHP TutorialWhen should we use exceptions?_PHP Tutorial

When should we use exceptions?_PHP Tutorial

Jul 20, 2016 am 10:58 AM
indivualusecompanyexistabnormalusSignificantof

Let me digress first: I have done two things in the company that I think are very meaningful. The first is to set up a PHP email group, and the second is to set up a Hi group. Currently, both There are more than 500 phpers in it. I have always believed that building a communication platform so that students can communicate smoothly and simply is the basis and prerequisite for creating a positive technical learning atmosphere. So that everyone's problems will not become other people's problems. , is the most direct benefit. (Postscript: Many people have asked for the email group address. I’m really sorry. This email group is an internal email group of the company, and Hi is also an internal email group of the company. Thank you)

Yesterday, A colleague raised a question in the email group:

When should Exception be used in PHP? How does it perform?

This issue can be regarded as a classic issue that has been debated for a long time. Let me talk about my personal opinion.

What are the error codes (or status codes) corresponding to exceptions? Advantages, disadvantages, how should we use them?

Error code

First of all, the exception mechanism only appeared after the error code mechanism, so according to the theory of evolution, Exceptions naturally avoid some shortcomings of the error code mechanism. These shortcomings include.

1. The error information is not rich

function, which can only have one return value (of course , Lua can return multiple, but it is actually equivalent to returning an array in PHP). The most common function description we have seen is: return *** when successful, and return FALSE when error occurs. However, there may be reasons for a function error. There are many types of errors. A simple FALSE cannot tell the caller the specific error message.

So, we have seen some function descriptions like this: If the return value If it is greater than 0, it indicates a successful status code. If the return value is less than 0, it indicates an error status code.

However, this requires the function to return an integer (or number). For some other functions, we cannot It is judged by 0, >0,

Therefore, some functions use global error codes and error messages to save specific error messages. At this time we see such a function description: Return *** successfully, error When it returns FALSE, the error code is stored in the global variable $errno (at least this is how most Linux library functions are described, haha).

Okey, this method can indeed work, but do you think, Is it ugly?

2. Adding an error status code may require changing the function signature

Suppose, you write a function, this function is very simple, very simple, you Thinking that it will never go wrong, you declare it as (using C language as an example, PHP has no return type hint):

<ol class="dp-c">
<li class="alt"><span><span>void dummy() {  </span></span></li>
<li><span>} </span></li>
</ol>

But then you slowly modified this function and gave it more function, this function may fail at this time. And you can't add an error return code to this function at all now.

Some people may say that PHP has no return value type restrictions, but think about the structure of PHP Functions and constructors have no return value. When an error occurs, if you do not use exceptions, I think you can only choose to die, or use the method in 2 to continue execution with the error.

In addition, In a good software system, the return type is actually a convention. When all functions used do not check the return value, you still cannot add an error return code to this function.

3. Error status codes may be ignored

What happens when one of your functions makes an error and returns an error status code, but the caller does not detect this return value? ? -_#. On the one hand, checking the return status code everywhere will cause the code to be very,ugly:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></span></li>
<li>
<span>  </span><span class="keyword">if</span><span> (!call1()) {  </span>
</li>
<li class="alt">
<span>      </span><span class="keyword">die</span><span>();  </span>
</li>
<li><span>  }  </span></li>
<li class="alt">
<span>   </span><span class="keyword">if</span><span> (call2() != SUCCESS) {  </span>
</li>
<li>
<span>     </span><span class="keyword">die</span><span>();  </span>
</li>
<li class="alt"><span>  }  </span></li>
<li>
<span>   </span><span class="keyword">if</span><span> (call3() </span>
</li>
<li class="alt">
<span>      </span><span class="vars">$msg</span><span> = error_get_last();  </span>
</li>
<li>
<span>      </span><span class="keyword">die</span><span>(</span><span class="vars">$msg</span><span>[</span><span class="string">"message"</span><span>]);  </span>
</li>
<li class="alt"><span>  } </span></li>
</ol>

Exception mechanism

So now we Let’s take a look at the exception mechanism. If we use the exception mechanism, the above code can be written as:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></span></li>
<li><span>try {  </span></li>
<li class="alt"><span>   call1();  </span></li>
<li><span>   call2();  </span></li>
<li class="alt"><span>   call3();  </span></li>
<li>
<span>} catch (Exception </span><span class="vars">$e</span><span>) {  </span>
</li>
<li class="alt">
<span>   </span><span class="keyword">die</span><span>(</span><span class="vars">$e</span><span>->getMessage());  </span>
</li>
<li><span>} </span></li>
</ol>

More conveniently, if your code is just the middle layer and your caller will be responsible for handling errors, you It can even be simply written:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></span></li>
<li>
<span class="keyword">function</span><span> myFunc() {  </span>
</li>
<li class="alt"><span>   call1();  </span></li>
<li><span>   call2();  </span></li>
<li class="alt"><span>   call3();  </span></li>
<li><span>} </span></li>
</ol>

And an exception object can contain richer error information, such as error message, error code, wrong number of lines, file, and even error context, etc. Avoid The shortcomings of "1. The error information is not rich".

We can also add exceptions to a function that returns void type without changing its function signature, so there will be no "2" mentioned above. Adding an error status code may require changing the function signature. For PHP, if the newly added error is not caught, don’t worry, it will obviously go wrong. The above mentioned "3. Error status" will not happen. code may be ignored".

However, there are also some voices against the use of exceptions:

1. Performance

As asked at the beginning of the article in: “How does it perform? ", the exception mechanism is indeed more expensive than the method of returning status code. For C++, when an exception occurs, stack unwinding also occurs.

Performance and convenience are often a contradiction. I It can only be said that you need to make trade-offs. If you are writing a small module, and its life cycle may be short, and it does not require any special design patterns, then I think you can do without exceptions.

而如果你在为一个庞大的软件做开发, 我想你更应该看重的, 应该是, 它的可扩展性, 可维护性.

2. 太多可能的Uncaught Exception

如果, 你调用了一个可能发生异常的函数, 但是却没有捕获这个异常, okey, Fatal Error了, 所以让我们的代码看起来:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></span></li>
<li><span>try {  </span></li>
<li class="alt"><span>} catch () {  </span></li>
<li><span>}....  </span></li>
<li class="alt"><span> try {  </span></li>
<li><span>} catch () {  </span></li>
<li class="alt"><span>}....  </span></li>
<li><span>try {  </span></li>
<li class="alt"><span>} catch () {  </span></li>
<li><span>} </span></li>
</ol>

然而, 这个是可以经过良好设计避免的, 比如我在设计

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445671.htmlTechArticle先说个题外话: 在公司做了俩件事, 是我觉得很有意义的, 第一就是成立了一个PHP邮件组, 第二就是成立了一个Hi群. 目前俩者都有超过500 ph...
Statement
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
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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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.