Summary of PHP error handling methods_PHP tutorial

WBOY
Release: 2016-07-20 11:12:01
Original
1035 people have browsed it

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
 代码如下 复制代码


//打开一个文件 未做任何处理
//$fp =fopen("aa.txt","r");
//echo "OK";

//处理:判断文件是否存在 file_exists
/*
if(!file_exists("aa.txt")){
echo "文件不存在";
//不存在就退出
exit(); //退出后,下面面的代码就不执行了
}else{
$fp =fopen("aa.txt","r");
//...操作完之后 关闭
fclose($fp);

}

echo "OK";
*/
//PHP处理错误的3种方法

//第一种:使用简单的die语句

/* if(!file_exists("aa.txt")){

die("文件不存在。。。"); //不存在就直接退出
}else{
$fp =fopen("aa.txt","r");
//...操作完之后 关闭
fclose($fp);

}

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

The code is as follows Copy code
 代码如下 复制代码

//
/*
使用error_function(error_level,error_message,
error_file,error_line,error_context)
该函数必须有能力处理至少两个参数 (error level 和 error message),
但是可以接受最多五个参数(可选的:file, line-number 以及 error context):

*/

//改写set_error_handler方法
//如果出现 E_WARNING 这个错误就调用my_error 处理方法
set_error_handler("my_error",E_WARNING);
set_error_handler("my_error2",E_USER_ERROR);
//设置中国对应的时区
date_default_timezone_set('PRC');

function my_error($errno,$errmes){

echo "$errno"; //输出错误报告级别
        echo "错误信息是:".$errmes;
        exit();
    }

    function my_error2($errno,$errmes){
       
        //echo "错误信息是:".$errno,$errmes;
        //exit();
        //把错误信息输入到文本中保存已备查看 使用到error_log()函数
        $message ="错误信息是:".$errno." ".$errmes;
        error_log(date("Y-m-d G:i:s")."---".$message."rn",3,"myerror.txt"); // rn 表示换行
    }

    //打开一个文件 未做任何处理

    //$fp =fopen("aa.txt","r");
    //echo "OK";

    //使用自定义错误 要添加触发器 这个trigger_error()函数来指定调用自定义的错误
    $age=200;
    if($age>150){
        //echo "年龄过大";
        //调用触发器 同时指定错误级别 这里需要查看帮助文档
        trigger_error("不好了出大问题了",E_USER_ERROR);
        //exit();
    }


?>

// /*

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:

try {
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';
 }

//捕获异常
catch(Exception $e)
 {
 echo 'Message: ' .$e->getMessage();
 }
?>

Copy code

//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;
 代码如下 复制代码

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();
 }
?>

}

//Trigger exception in the "try" code block
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(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. ...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template