Home > Backend Development > PHP Tutorial > Introduction to error and exception handling in php (code example)

Introduction to error and exception handling in php (code example)

不言
Release: 2023-04-05 13:10:02
forward
2381 people have browsed it

This article brings you an introduction to error and exception handling in PHP (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Three ways of php error handling

A: Simple die() statement

Equivalent to exit();

B: Custom errors and error triggers

1. Error handler (custom error, generally used for syntax error handling)

Create a defined error function (processor ), the function must be capable of handling at least two parameters (error_level and error_message), but can accept up to five parameters (erroe_file, error_line, error_context)

Syntax:

function error_function($error_level,$error_message,$error_fiel,$error_line,$error_context)
//创建好后还需要改写一个set_error_handler()函数
set_error_handler(‘error_function,E_WARNING’)//这里error_function对应上面创建的自定义处理器名,第二个参数为使用自定义错误处理器的错误级别。
Copy after login

Error level:

These error reporting levels are different types of errors that error handlers are designed to handle:

## E_WARNINGNon-fatal run-time error. Do not pause script execution. 8E_NOTICERun-time notification. Script discovery errors can occur, but they can also occur while the script is running normally. 256E_USER_ERRORFatal user-generated error . This is similar to E_ERROR set by the programmer using the PHP function trigger_error(). 512E_USER_WARNINGNon-fatal user-generated warn. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error(). 1024E_USER_NOTICE User-generated notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error(). 4096E_RECOVERABLE_ERRORCatchable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (See set_error_handler())##8191

Value

Constant

Description

##2

##E_ALL

All errors and warnings except level E_STRICT. (In PHP 6.0, E_STRICT is part of E_ALL)

2.错误触发器(一般用于处理逻辑上的错误)

需求:比如要接受一个年龄,如果数字大于120,就认为是个错误

传统方法:

<?php
if($age>120){
echo(’年龄错误’);
exit();
}
?>
Copy after login

使用触发器:

<?php
if($age>120){
trigger_error(‘年龄错误’);
}
//自定义处理器
function myerror(¥error_level,¥error_message){
echo ‘error text’;
}
//同时需要改变系统默认的处理器函数
set_error_handler(‘myerror’,E_USER_WARNING);
?>
Copy after login

C:错误日志

默认的根据php.ini中error_log配置,PHP向服务器的错误记录系统或文件发送错误记录。通过使用error_log()函数可以向文件或者远程目的地发送错误记录。

语法:

error_log(error[,type,destination,headers])
Copy after login

Type部分一般用3,表示在文件后面追加错误信息,而不会覆盖原内容destination表示目的地,即存放的文件或远程目的地

如:

error_log(“$error_info”,3,”errors.txt”);
Copy after login

二. php 异常处理

1.基本语法

<?php
try{
//可能出现异常或者错误的代码
//catch 捕获异常
}catch(Exception $e){
//对异常处理,方法
//1.自己处理
//2.不处理,可以再次抛出throw new Exception(‘XXX’);
}
?>
Copy after login

2.处理程序应当包括:

1.try—使用异常的函数应该位于‘try’代码块内,如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,或抛出一个异常;

2.throw — 这里规定如何触发异常,每一个“throw”必须对应至少一个‘catch’;

3.catch — ‘catch’代码块会捕获异常,并创建一个包含异常信息的对象。

eg:

<?php
/**
 * 创建可抛出一个异常的函数
 */
function checkNum($number) {
    if ($number > 1) {
        throw new Exception("Value must be 1 or below");
    }
    return true;
}
// 在 "try" 代码块中触发异常
try {
    checkNum(2);
    // 如果异常被抛出,那么下面一行代码将不会被输出
    echo &#39;If you see this, the number is 1 or below&#39;;
} catch (Exception $e) {
    // 捕获异常
    echo &#39;Message: &#39; . $e->getMessage();
}
?>
Copy after login

例子解释:

上面的代码抛出了一个异常,并捕获了它:

  1. 创建 checkNum() 函数,它检测数字是否大于 1,如果是,则抛出一个异常。

  2. 在 "try" 代码块中调用 checkNum() 函数。

  3. checkNum() 函数中的异常被抛出。

  4. "catch" 代码块接收到该异常,并创建一个包含异常信息的对象 ($e)。

  5. 通过从这个 exception 对象调用 $e->getMessage(),输出来自该异常的错误消息。

 异常的规则:

  • 需要进行异常处理的代码应该放入try代码块内,以便捕获潜在的异常

  • 每个try或者throw代码块必须至少一个对应的catch代码块

  • 使用多个catch代码块可以捕获不同种类的异常

  • 可以在try代码内的catch代码块中再次输出(re_throw)异常。

总结:简而言之,如果抛出了异常,就必须捕获他。

The above is the detailed content of Introduction to error and exception handling in php (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
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