Home Backend Development PHP Tutorial When should we use exceptions?_PHP Tutorial

When should we use exceptions?_PHP Tutorial

Jul 20, 2016 am 10:58 AM
indivual use company exist abnormal us Significant of

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, <0, and, even in this way, we still need to use the returned error code and some predefined macros (or call something like strerror()) to get a specific, readable Error message.

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>
Copy after login

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></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() < 0) {  </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>
Copy after login

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></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());  </p>
<li><span>} </span></li>
<p> 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: </p>
<pre class="brush:php;toolbar:false"><ol class="dp-c">
<li class="alt"><span><span><?php  </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>
Copy after login

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></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>
Copy after login

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

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

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

A guide to the unusual missions in the Rise of Ronin Pool A guide to the unusual missions in the Rise of Ronin Pool Mar 26, 2024 pm 08:06 PM

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection Jun 08, 2024 pm 06:09 PM

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

See all articles