Why do we need to use PHP exception codes? What are the usage scenarios of PHP exception code?
P粉476547076
P粉476547076 2023-08-24 12:31:44
0
2
483
<p>Okay, this is a very stupid question for many people, but I hope to get an overwhelming response :)</p> <p>When I throw an exception in PHP, I can add a code to the message. </p><p> I catch the exception and handle it based on its type (like <code>InvalidArgumentException</code> or <code>OutOfBoundException</code>). I log the <strong>message</strong> or display it, or otherwise handle it appropriately. </p><p> I can also attach a previous exception to trace the error's origin path. </p> <p>However, there is one thing I have never used or considered: how useful is the code? </p> <p>For example: </p> <pre class="brush:php;toolbar:false;">throw new Exception("db Error", $code, $previousException);</pre> <p>What should I do with <code>$code</code>? </p>
P粉476547076
P粉476547076

reply all(2)
P粉807239416

How to interpret $code depends on the exception type. For example, if you have a Exception subclass that represents a MySQL database error, then $code might be the native MySQL error code. In the case of low-level IO errors, this may be the value from <errno.h>.

Basically, $code should contain what you need to handle the exception programmatically. Most exceptions should be handled somewhere. If all your exceptions just show up as errors, then $code is only useful if you need to include error codes from something like a MySQL client library.

P粉891237912

This message is for display to the user, while the code is for your program to use. So for example, in your "Database Error" example, you could write a set of code like this:

  1. unable to connect
  2. Query error
  3. The result is empty
  4. Close connection error

Then use the corresponding code. When other parts of the code encounter an exception, they will know what happened and may be able to handle it intelligently.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!