Exception handling mechanism for PHP

Source: Internet
Author: User
Tags getmessage parse error php script 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:

<? PHP Try {    echo 1/0catch (Exception$e) {    Echo  $e-GetMessage ();}

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

The results show that a warning level error occurred and the program terminated. Conclusion: PHP is usually unable to automatically capture meaningful anomalies, which treat all anomalies as errors, and if you want to catch exceptions you have to use the IF....ELSE structure, ensure that the code is normal, and then decide to throw the exception manually.
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; Partial: Ini_set ("Display_error",true/false); PHP.ini in Display_errors=off to resolve the problem: PHP settings file php.ini has been set display_errors=Off, but there is still an error message on the page during the run. Solution: After the inspection log_errors= ON, according to the official statement, when this log_errors is set to ON, then the Error_log file must be specified, if not specified or the specified file does not have permission to write, then output to the normal output channel, then it makes display_errors The specified off fails, 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)
E_error a fatal run error. The error cannot be resumed and execution of the script is paused. E_warning Run-time warning (non-fatal error). Non-fatal run error, script execution does not stop. E_parse compile-time parsing error. Parsing errors are generated only by the parser. E_notice runtime reminders, which are often caused by bugs in your code, may also be intentional behavior. ) E_core_error a fatal error during initialization of PHP startup. E_core_warning a warning (non-fatal error) during initialization of PHP startup. E_compile_error compile-time fatal error. This is like a e_error generated by the Zend scripting engine. E_compile_warning compile-time warnings (non-sexual errors). This is like a e_warning warning generated by the Zend scripting engine. E_user_error the custom error message. E_user_warning a custom warning message like a PHP function trigger_error (Programmer settings E_error). E_user_notice A custom reminder message like a PHP function Trigger_error (programmer-Set e_warning warning). Like by using PHP function Trigger_error (programmer e_notice Set) e_strict coding standardized warning. Allows PHP to recommend modifying the code to ensure optimal interoperability forward compatibility. E_recoverable_error to catch a fatal error. Like E_error, but can be captured through user-defined processing (see also Set_error_handler ()) E_all all errors and warnings (not including e_strict) (E_strict will is part of E_all as of PHP6.0) - 16384e_user_deprecated the 30719E_all
A total of 15, using binary substitution,0000000000000011  represents e_error and e_warning for example: error_reporting (   3);  Show only E_error and e_warning error error_reporting (-1);   = on/off;  = php_errors.log//Set error log file (generated at the current location without a given path at this time) 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.

Like what:

<?PHP//mode One//Set_error_handler (' myerror ');//function Myerror ($errorNum, $errorMs, $errorFile, $errorLine) {//Echo (' set_ Error_Handler: '. $errorNum. ‘:‘ . $errorMs. ' In '. $errorFile. ' On '. $errorLine. ' line ');//}//mode twoclasserrorclass{//must static public method     Public Static functionMyerror ($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

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 there is this method, the corresponding error_reporting () can not 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)
Error capturing PHP: Fatal error, Parse error, etc., this method is the last function called before the end of the php script execution, such as a script error, die (),exit, exception, the normal end will be called. 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 [Lin E]             -the line where the error occurred note:This function is not called when Parse-time is faulted. This function is called only when run-time is faulted. This function is required to be successfully registered for use. "Test 3 vs. Test 4"

Like what:

<?PHPTry {    $a= 1/0;} Catch(Exception $e) {    Echo"Cat not divied by 0";} register_shutdown_function(' Myshutdownfunc ');functionMyshutdownfunc () {if($error=Error_get_last ()) {        Echo"<pre>"; Print_r($error); Echo"</pre>"; die; }}

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

Array (    [Type] = 2    [message] = Division by zero    [file] =    = D:\web\mytest\test.php [Line] = > 4)

Back to top 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.
Null

Like what:

<?PHP//first method of putting//function myexception ($exception) {//echo "<b>Exception:</b>", $exception->getmessage () ;//}//Set_exception_handler (' myexception ');//The second methodclassmyerror{//must be static public method     Public Static functionMyException ($exception) {        Echo"<b>Exception:</b>",$exception-GetMessage (); }}Set_exception_handler([' Myerror ', ' myexception ']);Throw New Exception(' No one handles exceptions ');

Output:Exception: No one handles the exception

Exception handling mechanism for PHP

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.