Analysis of Error Handling and exception handling mechanisms in PHP

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

Example: Copy codeThe Code is as follows: <? Php
$ A = fopen('test.txt ', 'R ');
// The file is opened without judgment. If the file does not exist, an error is returned.
?>

The correct statement should be as follows:Copy codeThe Code is as follows: <? Php
If(file_exists('test.txt ')){
Using fw.fopen('test.txt ', 'R ');
// Close after use
Fclose ($ f );
}
?>

I. PHP Error Handling Methods A. Simple die () statements;
Equivalent to exit ();
Example:Copy codeThe Code is as follows: if (! File_exists('aa.txt ')){
Die ('file does not exist ');
} Else {
// Perform the operation
}
// If the die () is triggered, the echo is not executed here.
Echo 'OK ';

Concise Syntax:Copy codeThe Code is as follows: file_exits('aaa.txt ') or die ('file does not exist ');
Echo 'OK ';

B. Custom errors and error triggers

1. Error processor (custom error, usually used for syntax error handling)
Create a custom error function (processor). This function must be able to process at least two parameters (error_level and errormessage), but can accept up to five parameters (error_file, error_line, error_context)
Syntax:Copy codeThe Code is as follows: function error_function ($ error_level, $ error_message, $ error_file, $ error_line, $ error_context)
// After creation, you need to rewrite set_error_handler (); Function
Set_error_handler ('error _ function', E_WARNING); // here, error_function corresponds to the custom processor name created above, and the second parameter is the error level of the custom error processor;

Error Report Level (learn more)

These error reporting levels are different types of errors that the error handler aims to handle:

Value Constant Description
2 E_WARNING Non-fatal run-time error. Do not pause script execution.
8 E_NOTICE

Run-time notification.

An error may occur when the script runs normally.

256 E_USER_ERROR Fatal user-generated error. This is similar to the E_ERROR set by the programmer using the PHP function trigger_error.
512 E_USER_WARNING Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error.
1024 E_USER_NOTICE User-generated notifications. This is similar to the E_NOTICE set by the programmer using the PHP function trigger_error.
4096 E_RECOVERABLE_ERROR Possible fatal errors. Similar to E_ERROR, but can be captured by a user-defined handler. (See set_error_handler ())
8191 E_ALL

All errors and warnings except level E_STRICT.

(In PHP 6.0, E_STRICT is part of E_ALL)

2. Error triggers (generally used to handle logical errors)
Requirement: for example, to receive an age, if the number is greater than 120, it is considered an error.
Traditional method:Copy codeThe Code is as follows: if ($ age> 120 ){
Echo 'Age error'; exit ();
}

Trigger:Copy codeThe Code is as follows: if ($ age> 120 ){
// Trigger_error ('error information' [, 'error level']); the error level is optional and is used to define the error level.
// User-defined levels include E_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE.
Trigger_error ('Age error'); // The default error handling method of the called system. You can also use a custom processor.
}
// Custom processor, same as above
Function myerror ($ error_level, $ error_message ){
Echo 'error text ';
}
// At the same time, you need to change the default processing function of the system.
Set_error_handler ('myerror', E_USER_WARNING); // same as above, the first parameter is the name of the custom function, and the second parameter is the error level. The error level here is generally the following: e_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE]
// Now trigger_error can be used to customize the error handling function.

Exercise questions:Copy codeThe Code is as follows: <? Php
Date_default_timezone_set ('prc ');
Function myerror ($ error_level, $ error_message ){
$ Info = "error code: $ error_level \ n ";
$ Info. = "error message: $ error_message \ n ";
$ Info. = 'occurrence time: '. date ('Y-m-d H: I: s ');
Using filename='aa.txt ';
If (! $ Fp = fopen ($ filename, 'A ')){
'File creation '. $ filename. 'failed ';
}
If (is_writeable ($ filename )){
If (! Fwrite ($ fp, $ info )){
Echo 'failed to write the file ';
} Else {
Echo 'error message recorded successfully ';
}
Fclose ($ fp );
} Else {
Echo 'file'. $ filename. 'unwriteable ';
}
Exit ();
}
Set_error_handler ('myerror', E_WARNING );
Using fpw.fopen('aaa.txt ', 'R ');
?>

C. Error Log
By default, according to The error_log configuration in php. ini, php sends error records to the server's error record system or file. You can use the error_log () function to send error records to files or remote destinations;
Syntax:
Error_log (error [, type, destination, headers])
The type part usually uses 3 to indicate appending an error message to the end of the file, instead of overwriting the original content.
Destination indicates the destination, that is, the stored file or remote destination.
For example, error_log ("$ error_info", 3, "errors.txt ");
Ii. PHP exception handling [Key]
1. Basic syntaxCopy codeThe Code is as follows: try {
// Code that may contain errors or exceptions
// Catch Exception is an Exception class defined by php
} Catch (Exception $ e ){
// Handle the exception. Method:
// 1. handle it by yourself
// 2. If it is not processed, throw it again
}

2. processing procedures should include:
Try-the abnormal function should be located in the "try" code block. If no exception is triggered, the Code continues as usual. However, if an exception is triggered, an exception is thrown.
Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
The Catch-"catch" code block captures exceptions and creates an object containing exception information.
Let's trigger an exception:Copy codeThe Code is as follows: <? Php
// Create a function that can throw an exception
Function checkNum ($ number ){
If ($ number> 1 ){
Throw new Exception ("Value must be 1 or below ");
}
Return true;
}
// Trigger an exception in the try code block
Try {
CheckNum (2 );
// If an exception is thrown, the following line of code will not be output
Echo 'if you see this, the number is 1 or below ';
} Catch (Exception $ e ){
// Capture exceptions
Echo 'message: '. $ e-> getMessage ();
}
?>

The above code will get an error similar to this:
Message: Value must be 1 or below
Example:
The above code throws an exception and captures it:
Create the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown.
Call the checkNum () function in the "try" code block.
An exception in the checkNum () function is thrown.
The "catch" code block receives the exception and creates an object ($ e) containing the exception information ).
Call $ e-> getMessage () from this exception object to output error messages from this exception.
However, to follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors.
The set_exception_handler () function can be used to set user-defined functions for handling all uncaptured exceptions.Copy codeThe Code is as follows: // set a top-level exception Processor
Function myexception ($ e ){
Echo 'this is top exception ';
} // Modify the default exception Processor
Set_exception_handler ("myexception ");
Try {
$ I = 5;
If ($ I <10 ){
Throw new exception ('$ I must greater than 10 ');
}
} Catch (Exception $ e ){
// Handle exceptions
Echo $ e-> getMessage (). '<br/> ';
// Continue to throw if the exception is not handled
Throw new exception ('errorinfo'); // you can use throw $ e to retain the original error message;
}

Create a custom exception classCopy codeThe Code is as follows: class customException extends Exception {
Public function errorMessage (){
// Error message $ errorMsg = 'error on line '. $ this-> getLine (). 'in '. $ this-> getFile (). ': <B> '. $ this-> getMessage (). '</B> is not a valid E-Mail address'; return $ errorMsg;
}
}
// Use
Try {
Throw new customException ('error message ');
} Catch (customException $ e ){
Echo $ e-> errorMsg ();
}

Multiple catch methods can be used to return error messages in different situations.Copy codeThe Code is as follows: try {
$ I = 5;
If ($ I> 0 ){
Throw new customException ('error message'); // use a custom exception class for processing
} If ($ I <-10 ){
Throw new exception ('error2 '); // use the default system exception
}
} Catch (customException $ e ){
Echo $ e-> getMessage ();
} Catch (Exception $ e1 ){
Echo $ e1-> getMessage ();
}

Abnormal rules
Code that requires exception handling should be placed in the try code block to capture potential exceptions. Each try or throw code block must have at least one catch code block. Multiple catch code blocks can capture different types of exceptions. You can throw a (re-thrown) exception again in the catch code block in the try code. In short: if an exception is thrown, it must be caught.

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.