Home Backend Development PHP Tutorial Summary of PHP error handling methods_PHP tutorial

Summary of PHP error handling methods_PHP tutorial

Jul 20, 2016 am 11:12 AM
php php5 exist deal with Summarize supply method have of mistake

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. ...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles