1、PHP The uniqueness of the anomalies in

  PHP The uniqueness of the anomaly in , namely PHP Exceptions in are different from mainstream languages C++、java The abnormal . stay Java in , Exceptions are the only way to report errors , And in the PHP Not so in China , Instead, we treat all abnormal situations as errors . The two languages have different definitions of exception and error . What is an exception, what is an error , Designers of the two languages have different views .

  PHP The abnormal :

   It is the situation that the program does not meet the expectation and is different from the normal process . An abnormal situation , A mistake that should not have been made by normal logic , But there will still be mistakes , This is a logical and business process error , Not compiler or syntax errors .

  PHP Mistakes in :

   It belongs to php The problem with the script itself , Most of the time it's the wrong grammar , The server environment causes , Make the compiler fail the check , Even if it doesn't work .warning、notice It's all mistakes , It's just that they're at different levels , And the mistake is that it can't be try-catch The captured .

   stay PHP Any self error encountered in the will trigger an error , Instead of throwing an exception .PHP In case of abnormal code , It usually triggers errors , Instead of throwing an exception . therefore , If you want to use exceptions to handle unexpected problems , It can't be done .

A typical example :


try {
echo 1/0;
} catch (Exception $e){
echo $e->getMessage();

Output :
Warning: Division by zero in D:\web\mytest\test.php on line 4

 Results show :

   A warning level error appears , Termination of procedure .

 Conclusion :
  PHP It's usually impossible to automatically catch meaningful exceptions , It sees all the anomalies as errors , If you want to catch exceptions, you have to use if....else structure , Make sure the code is normal , Then judge and manually throw an exception .

2、PHP Error level in

  PHP The exception mechanism in is insufficient , In most cases, you can't automatically throw an exception , You have to use if....else Sentence first judge , Throw an exception manually while you're in progress .

   It doesn't make much sense to throw an exception manually , It's a mistake that has been anticipated , This way will make you fall into the complicated business logic judgment and processing .

   So we can customize the error handling function through some special functions , To take over PHP Native error handling functions , Then throw an exception .

   Next we need to understand PHP Some of the mistakes in .

 Error display control :

  【ALL Set up 】

   overall situation :php.ini Set in display_error = on/off;

   Local :ini_set("display_error", true/false);

  PHP.ini in display_errors = Off Solutions to failure 
   problem : PHP Settings file php.ini Zhongming has set display_errors = Off, But in the process of running , Error messages still appear on the web page .
   solve : the check log_errors= On, According to the official , When this log_errors Set to On, Then you have to specify error_log file , If you do not specify or the specified file does not have permission to write , Then you'll still lose Out to the normal output channel , So it makes display_errors This designated Off invalid , The error message is still printed . So will log_errors = Off, The problem is solved .   【 Selective settings display error 】    overall situation :error_reporting = E_ALL | E_STRICT....    Local :error_reporting(E_ERROR | E_WARNING | E_PARSE)
E_ERROR            Fatal operation error . The error cannot be recovered , Pause script execution .
E_WARNING Runtime warning ( Non fatal error ). Non fatal running error , Script execution doesn't stop .
E_PARSE Compile time parsing error . Parsing errors are only generated by the parser .
E_NOTICE Run time reminders ( These are often in your code bug Caused by the , It can also be caused by intentional behavior .)
E_CORE_ERROR PHP Fatal error during initialization at startup .
E_CORE_WARNING PHP Warnings during initialization at startup ( Non fatal mistake ).
E_COMPILE_ERROR Fatal compile time error . It's like being driven by Zend The script engine generates a E_ERROR.
E_COMPILE_WARNING Compile time warnings ( Non causative error ). It's like being driven by Zend The script engine generated E_WARNING Warning .
E_USER_ERROR Custom error messages . Like with PHP function trigger_error( Programmer settings E_ERROR)
E_USER_WARNING Custom warning messages . Like with PHP function trigger_error( The programmer set up E_WARNING Warning )
E_USER_NOTICE Custom alert messages . Like by using PHP function trigger_error( The programmer E_NOTICE Set )
E_STRICT Code standardization warning . allow PHP It is recommended to modify the code to ensure the best interoperability and compatibility .
E_RECOVERABLE_ERROR It's a fatal mistake . image E_ERROR, But it can be captured through user-defined processing ( See you again set_error_handler())
E_ALL All the mistakes and warnings ( barring E_STRICT) (E_STRICT will be part of E_ALL as of PHP 6.0) E_USER_DEPRECATED E_ALL
 There are fifteen , Use binary instead of ,     Express  E_ERROR and E_WARNING

   for example :

  error_reporting();  // Display only E_ERROR and E_WARNING error 

  error_reporting(-);  // Only show all errors 

  Be careful :

   In the development phase, it's usually to show all the errors , Easy to solve problems ;

   In the production phase, it's usually hidden errors , And record the error to the file ( Error log );

  php.ini Set in :log_error = on/off;  // Record 、 Don't record 

         error_log = php_errors.log  // Set the error log file ( If there is no given path, it will be generated at the current position )

   You can also use ini_set() Set it up .

3、PHP Exception handling in

  3.1、set_error_handler(error_function, error_type)

   Use set_error_handler(error_function, error_type) Function to set custom error handling functions , Take over the original error handling function .

such as :


//  Mode one 
// set_error_handler('myError');
// function myError($errorNum, $errorMs, $errorFile, $errorLine){
// echo('set_error_handler: ' . $errorNum . ':' . $errorMs . ' in ' . $errorFile . ' on ' . $errorLine . ' line ');
// } // Mode two
class ErrorClass{
// It has to be static public Method
public static function myError($errorNum, $errorMs, $errorFile, $errorLine){
echo('set_error_handler: ' . $errorNum . ':' . $errorMs . ' in ' . $errorFile . ' on ' . $errorLine . ' line ');
} set_error_handler(['ErrorClass', 'myError']); try {
$a = 1/0;
} catch (Exception $e) {
echo "666";

Output :set_error_handler: 2:Division by zero in D:\web\mytest\test.php on 21 line

 From the results : We customize myError Method intercepts errors , At this point, we can take the initiative to deal with these errors , Throw the corresponding exception .

   But we need to pay attention to the following two points :

   First of all , If there is such a method , Corresponding error_reporting() You can't use it anymore . It will take over PHP Native error handling functions , That is, all errors will be handled by the custom function .
   second , This method cannot handle the following levels of errors :E_ERROR、 E_PARSE、 E_CORE_ERROR、 E_CORE_WARNING、 E_COMPILE_ERROR、 E_COMPILE_WARNING,set_error_handler() Function in the file E_STRICT, This function can only capture some of the Warning、Notice Level error .
Be careful :
   If an error occurs before the script is executed , Because the custom error handler has not been registered at this time , So you don't need this custom error handler .


   Capture PHP Error of :Fatal Error、Parse Error etc. , The method is PHP The last function called before the end of script execution , Like script errors 、die()、exit、 abnormal 、 It will be called at the normal end .
   Through this function, you can judge whether there is an error before the end of the script , Now we have to use a function :error_get_last(); This function can get all the errors generated by this execution .error_get_last(); Information returned :
  [type] - Wrong type
  [message] - Error message
  [file] - The file where the error occurred
  [line] - The line where the error occurred
Be careful : When parse-time This function will not be called in case of error . Only in run-time When something goes wrong , Will call this function . That is, you need to successfully register this function to use .【 test 3 And testing 4 contrast 】

such as :


try {
$a = 1/0;
} catch (Exception $e) {
echo "cat not divied by 0";
} register_shutdown_function('myshutdownfunc');
function myshutdownfunc()
if ($error = error_get_last()) {
echo "<pre>";
echo "</pre>";die;

Output :
Warning: Division by zero in D:\web\mytest\test.php on line 4

[type] => 2
[message] => Division by zero
[file] => D:\web\mytest\test.php
[line] => 4


Parameters describe
error_function It's necessary . Specifies the function to call when an uncapped exception occurs .
The function must be called set_exception_handler() Function .
This exception handler requires an argument , That is, throw out exception object .
 effect :

  set_exception_handler()  Function to set user-defined exception handling functions .

   This function is used to create the user's own exception handling method during runtime .

   This function returns the old exception handler , If it fails , Then return to  null.

 Tips : After the exception handler is called , The script will stop executing . 

such as :

// The first method is
// function myException($exception) {
// echo "<b>Exception:</b> " , $exception->getMessage();
// }
// set_exception_handler('myException'); // The second method
class MyError{
// It has to be static public Method
public static function myException($exception) {
echo "<b>Exception:</b> " , $exception->getMessage();
set_exception_handler(['MyError', 'myException']);
throw new Exception(' No one handles exceptions ');

Output :Exception:  No one handles exceptions

PHP More articles about exception handling mechanism of

  1. Java Exception handling mechanism try-catch-finally analyse

    Java Has a powerful exception handling mechanism , Recently, I have a preliminary study , I think it's a lot of content , I would like to share my understanding with you . One .  stay Java Code code in , Due to the use Myeclipse IDE, Can automatically remind users where there is ...

  2. JAVA Exception handling mechanism

    It mainly talks about several points : One . An introduction to anomalies Two . Exception handling process 3、 ... and . Runtime and non runtime exceptions Four .throws and throw keyword One . Introduction of abnormal Exception handling is what happens when a program is running , For example, divisor zero . Exception class (Except ...

  3. In depth understanding of java Exception handling mechanism

        Abnormality refers to all kinds of unexpected situations , Such as : The file could not be found . Network connection failed . Illegal parameters, etc . An exception is an event , It happens while the program is running , It interferes with the normal instruction flow .Java through too API in Throwable Many subclasses of a class describe different kinds of ...

  4. C++ Learning notes 27: Exception handling mechanism

    One . The foundation of exception handling mechanism Definition of exception Abnormal operation that can be detected in the program The basic process of exception handling There is a special situation in the execution of a program code , Throw a specific exception Another piece of program code catches the exception and handles it Two . Exception initiation th ...

  5. C++ The exception handling mechanism in

    C++ Capture exception mechanism in catch The types of arguments in the arguments are different , The treatment is different , And it's not the same as ordinary function calls , Specifically, when an exception is thrown throw A() or throw obj when , Object will do an additional object copy operation ...

  6. 16、java The exception handling mechanism in

    abnormal : That is, the program is abnormal when it is running . The origin of the anomaly : The problem is also a concrete thing in real life , It can also be done through java In the form of a class . And encapsulate it as an object . In fact, that is java After describing the abnormal situation, the object reflects . The delimitation of the problem ...

  7. Struts——( Four ) Exception handling mechanism

    Under normal circumstances , When we get the exception , You need to navigate the page to an error page , Error message . utilize Stuts We can handle exceptions in two ways : 1. Programming exception handling That is, we are in Action When invoking the method of the business logic layer object , ...

  8. Java Exception handling mechanism of object oriented programming

    One :Java The advantages of the exception handling mechanism of : 1: Classify the anomalies of different situations , Use JAVA Class to represent an exception , This kind of class is called exception class . All kinds of exceptions are represented as exception classes , Can give full play to the class scalability and reusability . 2: Abnormal flow ...

  9. Java Exception handling mechanism

    source : In depth understanding of java Exception handling mechanism 2.Java abnormal     Abnormality refers to all kinds of unexpected situations , Such as : The file could not be found . Network connection failed . Illegal parameters, etc . An exception is an event , It happens while the program is running , It interferes with the normal instruction flow .Java through ...

  10. SpringMVC Detailed explanation of exception handling mechanism [ With source code analysis ]

    Catalog Preface Introduction to important interfaces and classes HandlerExceptionResolver Interface AbstractHandlerExceptionResolver abstract class AbstractHandlerMethodE ...

Random recommendation

  1. Nodejs operation redis

    //npm install redis // First load node_redis modular var redis = require('redis'); // establish redis Connect var client = redis ...

  2. MYSQL Summary of various cases of index failure

    1) No query criteria , Or the query criteria are not indexed   2) No guide column is used on the query criteria   3) The number of queries is a large part of the large table , Should be 30% above .  4) Index itself is invalid 5) Query conditions use functions on index columns , Or to the rope ...

  3. hdu 1228 A+B string manipulation Super big water problem

    The Chinese meaning is not explained . Very water , I wanted to use switch Processing strings , Then the compilation doesn't pass ... original switch It can only deal with integer type , I forgot to . And then there's a whole bunch of frustrations if Code. ... Code : #include < ...

  4. Unity Simulation of Dragon Valley characters walking simple control

    I personally like Dragon Valley (DN) It's controlled by people ( It's not an ad ....), It's just that the characters are a little cute , action . The sense of attack is very good . Use today Unity A simple imitation of DN Character control of , Of course , There are many actions in the game , I've just done a simple w ...

  5. OSI First knowledge of reference model

    In memory of the digital communication I once loved (^o^). 1.osi Reference model 2. Encapsulation and de encapsulation of data 3. Communication between hosts

  6. An annotation based command line parser

    Java Command line options parsing Commons-CLI & Args4J & JCommander http://rensanning.iteye.com/blog/2161201 JComm ...

  7. API Two ways to turn pages

    Developing API When , Sometimes there's too much data , It needs to be paged . Offset based paging (Offset-based) This way is to provide a number of pens per page (page size) To define the maximum number of returned entries , Provide a page number (page ...

  8. Elastic layout --flex Direction

    flex Direction flex The direction is determined by flex-direction Characteristics determine , Used to define flexible layout patterns .flex-direction share 4 Patterns : From left to right . From right to left . From the top down . From bottom to top . Spindle The starting point and the ending point of the spindle define ...

  9. network install Centos x64 6.10

    1. Download laomaotao PE The latest enhancements , Then generate a bootable U disc . 2. stay U Create a directory on your hard disk or mobile hard disk MYEXT, And then put centos Installation iso Put it in there . 3. Guide selection from outside ISO Installation . https:// ...

  10. What we need to register is that we have another one “ Intersection ” cross join,  such Join There's no way to express it in a diagram , Because it's a watch A And table B Data for a N*M The combination of , Cartesian product . The expression is as follows :

              What we need to register is that we have another one " Intersection " cross join,  such Join There's no way to express it in a diagram , Because it's a watch A And table B Data for a N*M The combination of , Cartesian product . surface ...