PHP Exception Handling and Exception Handling

Source: Internet
Author: User
Tags parse error php exception handling

PHP Exception Handling and Exception Handling
1. uniqueness of exceptions in PHP

The uniqueness of exceptions in PHP is that exceptions in PHP are different from exceptions in mainstream languages C ++ and java. In Java, exceptions are the only way to report errors, but not in PHP. Instead, exceptions are treated as errors. The two languages have different definitions of exceptions and errors. What are exceptions and what are errors? The designers of the two languages have different opinions.

PHP exceptions:

It is a situation where the program is not in line with expectations and is different from the normal process. In an abnormal situation, errors that should not have been produced according to the normal logic, but still occur. This is a logical and business process error, rather than a compilation or syntax error.

PHP errors:

It is a problem of the php script itself. In most cases, it is caused by incorrect syntax and server environment, which makes the compiler unable to pass the check or even run. Both warning and notice are errors, but their levels are different, and the errors cannot be captured by try-catch.

In PHP, an error is triggered if any of its own errors occur, rather than throwing an exception. If PHP encounters an abnormal code, it usually triggers an error instead of throwing an exception. Therefore, exceptions cannot be used to handle unexpected problems.

Typical Example:

1 <?php2 3 try {4     echo 1/0;5 } catch (Exception $e){6     echo $e->getMessage();7 }

Result:

Result:

At this time, a warning-level error occurs and the program is terminated.

Conclusion: PHP usually cannot automatically capture meaningful exceptions. It regards all abnormal situations as errors. To capture exceptions, you must use if .... else structure to ensure that the Code is normal, and then manually throw an exception. 2. error levels in PHP

The exception mechanism in PHP is insufficient. In most cases, an exception cannot be automatically thrown. You must use the if... else statement to first judge and manually throw an exception.

  It is of little significance to manually throw an exception., Is an unexpected error. This method will put you into complicated business logic judgment and processing.

Therefore, we can use some special functions to customize error handler functions to take over native PHP error handler functions and then throw exceptions.

Next we need to understand some errors in PHP.

Error display control:

[ALL settings]

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

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

Solution for failure of display_errors = Off in PHP. ini 
Problem:In the PHP setting file php. ini, display_errors = Off is already set, but an error message still appears on the webpage during running.
Solution:Check log_errors = On. According to the official statement, when log_errors is set to On, the error_log file must be specified. If the specified file is not specified or the specified file has no permission to write data, as a result, it will still be lost to the normal output channel, which will invalidate the Specified Off display_errors and print the error message. Therefore, log_errors = Off will solve the problem.

[Display Error of selective settings]

Global: error_reporting = E_ALL | E_STRICT ....

Local: error_reporting (E_ERROR | E_WARNING | E_PARSE)

1 E_ERROR fatal running error. The error cannot be recovered. The script is paused. 2 E_WARNING runtime warning (non-fatal error ). Non-fatal running error. script execution will not stop. 4. parsing error during E_PARSE compilation. Parsing errors are only generated by the analyzer. 8 E_NOTICE runtime reminder (these are often caused by bugs in your code, and may also be caused by intentional behavior .) 16 E_CORE_ERROR fatal error during PHP initialization. 32 E_CORE_WARNING warning during initialization (non-fatal error) during PHP startup ). 64 E_COMPILE_ERROR fatal error during compilation. This is like an E_ERROR generated by the Zend script engine. 128 E_COMPILE_WARNING warning during compilation (non-inductive error ). This is like the E_WARNING warning generated by the Zend script engine. 256 E_USER_ERROR custom error messages. Like using the PHP function trigger_error (the programmer sets E_ERROR) 512 E_USER_WARNING to customize warning messages. Like trigger_error (programmer's E_WARNING warning) 1024 E_USER_NOTICE custom reminder message. Trigger_error (programmer's E_NOTICE set) 2048 E_STRICT encoding standardization warning. PHP is allowed to recommend code modification to ensure the best interoperability forward compatibility. 4096 E_RECOVERABLE_ERROR. Like E_ERROR, but can be captured through user-defined processing (see set_error_handler () 8191 E_ALL all errors and warnings (excluding E_STRICT) (E_STRICT will be part of E_ALL as of PHP 6.0) 14 16384 E_USER_DEPRECATED 15 30719 E_ALL

There are a total of 15 types, which are replaced by binary. 0000 0000 0000 0011 represents E_ERROR and E_WARNING

For example:

Error_reporting (3); // only display E_ERROR and E_WARNING errors

Error_reporting (-1); // only show all errors

Note:

In the development phase, all errors are usually displayed to help solve the problem;

Errors are usually hidden in the production phase, and errors must be recorded in files (error logs );

Set in php. ini: log_error = on/off; // record, not record

Error_log = php_errors.log // set the Error Log File (if no path is specified, the file is generated at the current location)

You can also set it through ini_set.

 

3. PHP Exception Handling 3.1, set_error_handler (error_function, error_type)

Use the set_error_handler (error_function, error_type) function to set a custom error handler to take over the original error handler function.

Eg.

1 <? Php 2 3 // Method 4 // set_error_handler ('myerror'); 5 // function myError ($ errorNum, $ errorMs, $ errorFile, $ errorLine) {6 // echo ('set _ error_handler :'. $ errorNum. ':'. $ errorMs. 'in '. $ errorFile. 'on '. $ errorLine. 'line'); 7 //} 8 9 // method 2 10 class ErrorClass {11 // The static public method must be 12 public static function myError ($ errorNum, $ errorMs, $ errorFile, $ errorLine) {13 echo ('set _ error_handler :'. $ errorNum. ':'. $ errorMs. 'in '. $ errorFile. 'on '. $ errorLine. 'line'); 14} 15} 16 17 set_error_handler (['errorclass', 'myerror']); 18 19 20 try {21 $ a = 5/0; 22} catch (Exception $ e) {23 echo "666666"; 24}

Access results:

The results show that the custom myError method intercepts errors. At this time, we can actively handle these errors and throw corresponding exceptions.

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

First, if this method exists, the corresponding error_reporting () cannot be used. It will take over the native PHP error handler function, that is, all errors will be handed over to the custom function for processing. Second, this method cannot handle the following errors: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and E_STRICT generated in the file where the set_error_handler () function is located, this function can only capture system-generated Warning and Notice-level errors. Note:If an error occurs before the script is executed, the custom error handler is unavailable because the custom error handler function is not yet registered. 3.2 register_shutdown_function (exception_function) catch PHP errors: Fatal Error, Parse Error, etc. This method is the last called function before PHP script execution ends, such as script Error, die (), exit, exception, and normal termination are all called. By using this function, you can determine whether an error is generated in this execution before the script ends. In this case, you need to use the error_get_last () function to obtain all the errors generated in this execution. Error_get_last (); returned information: [type]-Error type
[Message]-error message
[File]-file in which an error occurs
[Line]-row where an error occurs. Note: This function is not called when a parse-time error occurs. This function is called only when a run-time error occurs. This function must be successfully registered before it can be used. [Comparison of Test 3 and Test 4]

Eg.

 1 <?php 2                  3 try { 4     $a = 5/0; 5 } catch (Exception $e) { 6     echo "666666"; 7 } 8      9 register_shutdown_function('myshutdownfunc');10 function myshutdownfunc()11 {12     if ($error = error_get_last()) {13         echo "<pre>";14         print_r($error);15         echo "</pre>";die;16     }17 }

 

Test 1:

Test 2: (use echo "string"; replace try... catch)

Test 3: (replace try... catch with echo "string)

The syntax is incorrect. The register_shutdown_function is not executed.

 

Test 4:

Create a new file, php code with syntax errors, and introduce it into the execution file, such

1 ceshi2.class. php file 2 <? Php 3 echo "string" 4 5?> 6 7 ceshi. class. php file 8 <? Php 9 10 register_shutdown_function ('myshutdownfunc'); 11 function myshutdownfunc () 12 {13 if ($ error = error_get_last () {14 echo "<pre> "; 15 print_r ($ error); 16 echo "</pre>"; die; 17} 18} 19 20 include "ceshi2.class. php "; 21?>

Result:

3.3. set_exception_handler (exception_function)

 

Parameters Description
Error_function Required. Specifies the function called when an uncaptured exception occurs.
This function must be defined before the set_exception_handler () function is called.
This exception handling function requires a parameter, that is, the thrown exception object.

Purpose:

The set_exception_handler () function sets the custom exception handling function.

This function is used to create your own exception handling methods during runtime.

This function returns the old exception handler. If it fails, null is returned.

Tip: After the exception handler is called, the script stops running.

Eg.

1 <? Php 2 // method 3 // function myException ($ exception) {4 // echo "<B> Exception: </B> ", $ exception-> getMessage (); 5 //} 6 // set_exception_handler ('myexception '); 7 8 // method 2 9 class MyError {10 // it must be a static public method 11 public static function myException ($ exception) {12 echo "<B> Exception: </B> ", $ exception-> getMessage (); 13} 14} 15 set_exception_handler (['myerror', 'myexception']); 16 throw new Exception ('uncaught Exception occurred --- exceptions not handled ');

Running result:

 

Author: The leaf goes with the wind

Address: http://www.cnblogs.com/phpstudy2015-6/p/8433541.html

Disclaimer: This blog post is original and only represents the point of view or conclusion I have summarized at a certain time in my work and study. When reprinting, please provide the original article link clearly on the Article Page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.