On PHP exception handling

Source: Internet
Author: User
Tags getmessage parse error php exception handling throw exception zend

1. Unusual Uniqueness in PHP

The uniqueness of exceptions in PHP is that exceptions in PHP are different from those in mainstream languages C + + and Java. In Java, exceptions are the only way to report errors, not in PHP, but to treat all anomalies as errors. The two languages differ in the definition of anomalies and errors. What is an exception and what is wrong, the designers of both languages have different views.

  Exceptions in PHP:

Is that the program does not meet the expected situation in the operation and is different from the normal process. An abnormal situation, according to the normal logic should not be wrong, but still the error, this is a logical and business process errors, not compile or grammatical errors.

  Errors in PHP:

is the PHP script itself problem, most of the situation is caused by the wrong syntax, the server environment, so that the compiler can not pass the check, or even can not run the situation. Warning, notice are all errors, but their levels are different, and errors cannot be captured by Try-catch.

Any errors encountered in PHP will trigger an error instead of throwing an exception. when PHP encounters abnormal code, it usually triggers an error instead of throwing an exception. Therefore, if you want to use exceptions to handle unforeseen problems, it is impossible.

Typical examples:

1 <? PHP 2 3 Try {4     echo 1/0; 5 Catch (Exception$e) {6     Echo $e-GetMessage (); 7 }

Results:

The results show:

At this point a warning level error has occurred and the program terminates.

Conclusion:  PHP is usually unable to automatically catch a meaningful exception, it sees all the abnormal situation as an error, you want to catch the exception to use the IF....ELSE structure, to ensure that the code is normal, and then to determine the manual throw exception. 2. Error level in PHP

The exception mechanism in PHP is insufficient, in most cases cannot automatically throw an exception, you must use the If....else statement first to judge, in a manual throw exception.

  manually throwing exceptions is not very meaningful , it is a mistake that has been anticipated, and this approach will put you in the midst of complex business logic judgments and processes.

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

Next we need to understand some of the errors in PHP.

Error Display control:

"All Settings"

Global: php.ini Set display_error = ON/off;

Local: Ini_set ("Display_error", True/false);

resolution of display_errors = off failure in php.ini
Questions: PHP settings file php.ini has been set display_errors = Off, but during the run, the page will still appear error message.
Resolution: log_errors= on, according to the official statement, when this log_errors is set to ON, then you must specify the Error_log file, if not specified or the specified file does not have permission to write, so will output to the normal output channel, It also causes Display_errors to expire the specified off, and the error message is printed out. So the log_errors = Off, the problem is solved.

"Selective Settings Display Error"

Global: error_reporting = E_all | E_strict ....

Part: error_reporting (E_error | e_warning | E_parse)

1E_errora fatal run error. The error cannot be resumed and execution of the script is paused. 2e_warningRun-time warning (non-fatal error). Non-fatal run error, script execution does not stop. 4E_parsecompile-time parse error. Parsing errors are generated only by the parser. 8E_noticeRuntime Reminders (These are often caused by bugs in your code, or by intentional behavior.) )16E_core_errorfatal error during initialization of PHP at startup. 32e_core_warningwarnings during initialization of PHP startup (non-fatal error). 64E_compile_errorcompile-time fatal error. This is like a e_error generated by the Zend scripting engine. 128e_compile_warningCompile-time warning (non-sexual error). This is like a e_warning warning generated by the Zend scripting engine. 256E_user_errorcustom error messages. Like with PHP function Trigger_error (programmer set E_error)512e_user_warningA custom warning message. Like PHP function Trigger_error (programmer-Set e_warning warning)1024E_user_noticea custom reminder message. Like by using PHP function Trigger_error (programmer e_notice Set)2048e_strictCoding Normalization Warning. Allows PHP to recommend modifying the code to ensure optimal interoperability forward compatibility. 4096E_recoverable_error to catch a fatal error. Like E_error, but can be captured through user-defined processing (see also Set_error_handler ())8191E_allAll errors and warnings (not includinge_strict) (e_strictwould be part ofE_all  asof PHP 6.0) 16384 e_user_deprecated 15 30719E_all

A total of 15, using binary instead, 0000 0000 0000 0011 for E_error and e_warning

For example:

Error_reporting (3); Show only E_error and e_warning errors

Error_reporting (-1); Show all error errors only

Attention:

In the development phase is usually to display all errors, convenient to solve the problem;

In the production phase is usually a hidden error, and the need to log errors to the file (error log);

PHP.ini set: Log_error = ON/off; Record, do not record

Error_log = php_errors.log//Set error log file (no path given at this time is generated at the current location)

It can also be set by Ini_set ().

3. Exception Handling in PHP 3.1, Set_error_handler (Error_function, Error_type)

Use the Set_error_handler (error_function, Error_type) function to set the custom error handler to take over the original error handler.

eg.

1<?PHP2 3 //Way One4 //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 //Mode twoTen classerrorclass{ One     //must static public method A      Public Static functionMyerror ($errorNum,$errorMs,$errorFile,$errorLine){ -     Echo(' Set_error_handler: '.$errorNum. ‘:‘ .$errorMs. ' In '.$errorFile. ' On '.$errorLine. ' Line '); -     } the } -  - Set_error_handler([' Errorclass ', ' myerror ']); -  +  - Try { +     $a= 5/0; A}Catch(Exception $e) { at     Echo"666666"; -}

Access results:

The result shows that our custom Myerror method intercepts the error, at which point we can proactively handle these errors and throw the corresponding exceptions.

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

First, if the method is present, the corresponding error_reporting () cannot be used.  It will take over the PHP native error handler, which means that all errors will be passed to the custom function handler. Second, this method cannot handle errors at the following levels: E_error, E_parse, E_core_error, e_core_warning, E_compile_error, E_compile_warning,set_error_ The e_strict generated in the file where the handler () function only captures some warning, notice-level errors generated by the system. Note:  If an error occurs before the script executes, this custom error handler is not available because the custom error handler is not registered at this time. 3.2, Register_shutdown_function (exception_function) Catch PHP errors: Fatal error, Parse error, etc.,This method is the last function called before the end of the php script execution, such as script errors, die (), exit, exceptions, and normal end calls. This function can be used to determine whether the execution of this error occurred before the end of the script, it is necessary to use a function: Error_get_last (); This function can get all the errors generated by this execution. Error_get_last (); Returned information: [Type]-error type
[Message]-error message
[File]-the document where the error occurred
[Line]-the row where the error occurred note: This function is not called when Parse-time error occurs. This function is called only when the Run-time error occurs. This function is required to be successfully registered for use. "Test 3 vs. Test 4"

eg.

1<?PHP2                 3 Try {4     $a= 5/0;5}Catch(Exception $e) {6     Echo"666666";7 }8     9 register_shutdown_function(' Myshutdownfunc ');Ten functionMyshutdownfunc () One { A     if($error=Error_get_last ()) { -         Echo"<pre>"; -         Print_r($error); the         Echo"</pre>"; die; -     } -}

Test 1:

Test 2: (Use echo "string"; replace Try....catch)

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

Syntax error at this time, register_shutdown_function function not executed

Test 4:

Create a new file, PHP code with syntax errors, and introduce it into the execution file, for example

1Ceshi2.class.php file2<?PHP3 Echo"String"4 5?>6 7Ceshi.class.php file8<?PHP9 Ten register_shutdown_function(' Myshutdownfunc '); One functionMyshutdownfunc () A { -     if($error=Error_get_last ()) { -         Echo"<pre>"; the         Print_r($error); -         Echo"</pre>"; die; -     } - } +  - include"Ceshi2.class.php"; +?>

Results:

3.3, Set_exception_handler (exception_function)

Parameters Description
Error_function Necessary. Specifies the function that is called when an uncaught exception occurs.
The function must be defined before calling the Set_exception_handler () function.
This exception handler requires a parameter, the exception object that is thrown.

Role:

The Set_exception_handler () function sets the user-defined exception handling function.

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

The function returns the old exception handler, or null if it fails.

tip: After this exception handler is called, the script stops executing.

eg.

1<?PHP2 //The first method of placing3 //function MyException ($exception) {4 //echo "<b>Exception:</b>", $exception->getmessage ();5 // }6 //Set_exception_handler (' myexception ');7  8 //second method9 classmyerror{Ten     //must be static public method One      Public Static functionMyException ($exception) { A         Echo"<b>Exception:</b>",$exception-getMessage (); -     } - } the Set_exception_handler([' Myerror ', ' myexception ']); - Throw New Exception(' uncaught Exception occurred---No one handles the anomaly ');

Operation Result:

That leaves with the wind

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

Statement: This blog article for the original, only represents my work in the study in a certain time to summarize the views or conclusions. Please give the original link in the article page when reproduced

On PHP exception handling

Related Article

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.