search
HomeBackend DevelopmentPHP TutorialIntroduction to error and exception handling in php (code example)

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对应上面创建的自定义处理器名,第二个参数为使用自定义错误处理器的错误级别。

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

使用触发器:

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

C:错误日志

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

语法:

error_log(error[,type,destination,headers])

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

如:

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

二. php 异常处理

1.基本语法

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

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

例子解释:

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

  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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool