Summary of PHP error handling methods_PHP tutorial
WBOYOriginal
2016-07-20 11:12:011035browse
There are many error handling methods in php, especially after php5, special php processing classes are provided. Below I have collected some methods and programs about PHP error handling to share with you.
Judge directly in the program
Basic error handling: use the die() function The first example shows a simple script to open a text file:
The code is as follows
Copy code
代码如下
复制代码
$file=fopen("welcome.txt","r"); ?>
$file=fopen("welcome.txt","r");?>
If file does not exist, you will get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:webfoldertest.php on line 2
echo "OK"; */ //更简单的方式 file_exists("aa.txt") or die("文件不存在");
?>
More details
The code is as follows
Copy code
<🎜> //Open a file without any processing<🎜> //$fp = fopen("aa.txt","r");<🎜> //echo "OK";<🎜><🎜> //Processing: Determine whether the file exists file_exists<🎜>/*<🎜> if(!file_exists ("aa.txt")){<🎜> echo "The file does not exist";<🎜> //Exit if it does not exist<🎜> exit(); //After exiting, the following code will not be executed<🎜 > }else{<🎜> $fp =fopen("aa.txt","r");<🎜> }<🎜><🎜> echo "OK";<🎜>*/<🎜> //3 ways to handle errors in PHP <🎜><🎜> //The first one: use a simple die statement <🎜>< 🎜>/* if(!file_exists("aa.txt")){<🎜> <🎜> die("The file does not exist. . . "); //If it does not exist, exit directly <🎜> }else{<🎜> $fp =fopen("aa.txt","r");<🎜> fclose($fp);<🎜><🎜> }<🎜><🎜> echo "OK";<🎜>*/<🎜> //Simpler way<🎜> file_exists("aa.txt") or die("File does not exist");<🎜><🎜><🎜>?>
Second type: Error handler error level handling error method
// /* Use error_function(error_level, error_message,
error_file,error_line,error_context)
The function must be able to handle at least two parameters (error level and error message),
but can accept up to five parameters (optional: file, line -number and error context):
*/ //Rewrite the set_error_handler method
代码如下
复制代码
//create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }
//trigger exception checkNum(2); ?>
//If the error E_WARNING occurs, call the my_error processing method set_error_handler("my_error", E_WARNING); set_error_handler("my_error2",E_USER_ERROR); //Set the time zone corresponding to China date_default_timezone_set('PRC'); function my_error($errno,$errmes) { echo "& lt; font size = '5' color = 'red' & gt; $ errno & lt;/font & gt;" // Output error report level echo "error message is:". $ errmes; exit(); } function my_error2($errno,$errmes){ //echo "The error message is: ".$errno,$errmes ; //exit(); //Enter the error message into the text and save it for viewing. Use the error_log() function $message = "The error message is: ".$errno." " .$errmes; error_log(date("Y-m-d G:i:s")."---".$message."rn",3,"myerror.txt"); // rn means line break } //Open a file without any processing //$fp =fopen("aa.txt","r"); //echo "OK" ; //To use a custom error, add the trigger_error() function to specify the custom error to be called $age=200; if($age>150){ //echo "too old"; exit(); }?> PHP exception handling PHP 5 provides a new object-oriented error handling method If the exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then an exception will occur A serious error (fatal error), and an "Uncaught Exception" error message is output. Let's try throwing an exception without catching it:
The code is as follows
Copy code
//create function with an exception<🎜>function checkNum( $number)<🎜> {<🎜> if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }//trigger exceptioncheckNum(2);?>
The above code will get an error like this:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:webfoldertest.php:6 Stack trace: #0 C:webfoldertest.php(12): checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6Try, throw and catch to avoid the above example Errors, we need to create appropriate code to handle exceptions.
Handling handlers should include:
1.Try - Functions that use exceptions should be inside a "try" block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown. 2.Throw - This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch" 3.Catch - The "catch" code block will catch the exception and create an object containing the exception information Let us trigger an exception:
The code is as follows
代码如下
复制代码
//创建可抛出一个异常的函数 function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }
//在 "try" 代码块中触发异常 try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; }
class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': '.$this->getMessage().' is not a valid E-Mail address'; return $errorMsg; } }
$email = "someone@example...com";
try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } }
checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below';
}
//Catch exceptioncatch(Exception $e) { echo 'Message: ' .$e->getMessage(); }?> The above code will get an error like this:
Message: Value must be 1 or belowCreate a custom Exception Class
Creating custom exception handlers is very simple. We simply created a specialized class whose functions are called when an exception occurs in PHP. This class must be an extension of the exception class.
This custom exception class inherits all properties of PHP's exception class, and you can add custom functions to it. We start to create the exception class:
The code is as follows
Copy code
class customException extends Exception<🎜> {<🎜> public function errorMessage()<🎜> {<🎜> / /error message<🎜> $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': '.$this ->getMessage().' is not a valid E-Mail address'; return $errorMsg; } }$email = "someone@ example...com";try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { / /throw exception if email is not valid throw new customException($email); } }catch (customException $e) { //display custom message echo $e->errorMessage(); }?> This new class is a copy of the old exception class , plus the errorMessage() function. Just because it is a copy of the old class, it inherits the properties and methods from the old class, and we can use the methods of the exception class, such as getLine(), getFile(), and getMessage().
http://www.bkjia.com/PHPjc/444611.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444611.htmlTechArticleThere are many ways to handle errors in php, especially after php5, special php processing classes are provided. Below I have collected some methods and programs about PHP error handling to share with you. ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn