search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP exception handling, error reporting, and logging

In php we often encounter some errors to deal with. Let me summarize the exception handling, error reporting, and some logs in php Content summary and introduction.

Error handling:

1.Syntax error

2. Runtime error

3. Logic error

Error report:

Error: E_ERROT The program will be interrupted, an error occurred

Warning: E_WARNING The program will not be interrupted, but some functions may not be implemented

Note: E_NOTICE will not affect the program and can be completely blocked

Output all error reports during development and disable all error reports during runtime

Write errors to the log:

1. Turn on the log (error_log = On in php.ini), and turn off error reporting. The error (if it occurs, but direct output is not allowed) will be recorded in the log

2 .If the log path is not specified, it will be written to the web server log by default

Set error report:

error_reporting(E_ALL) //输出所有报告

Modify php.iniConfiguration file :

ini_set(“display_errors”,off) //修改为不显示错误报告
ini_get(“upload_max_filesize”) //读取配置文件中上传文件大小限制

Accidents are unexpected things that happen while the program is running. Use exceptions to change the normal flow of the script. Exception handling:

PHP 5 provides a new Object-oriented error handling method.

Exception handling is used to change the normal flow of a script when a specified error (exception) situation occurs. This situation is called an exception.

When an exception is triggered, what typically happens is:

• The current code state is saved
• Code execution is switched to predefined exception handling ProcessorFunction
•Depending on the situation, the processor may restart code execution from the saved code state, terminate script execution, or continue script execution from another location in the code
We will show Different error handling methods:

•ExceptionBasic use
•Create custom exception handler
•Multiple exceptions
•Re Throw an exception
•Set the top-level exception handler

Syntax:

try{
可能出错的代码
throw new Exception(“异常信息”)
}catch(Exception $e[异常对象]){
后面的正常代码
}

Example

function   runtimeErrorHandler($level,$string) 
{
//自定义错误处理时,手动抛出一个异常实例
//为了把错误级别代码也显示出来,这里拼接了错误代码和错误信息作为新的错误信息来传递。
throw   new   Exception($level.'|'.$string); 
} 
//设置自定义错误处理函数
set_error_handler( "runtimeErrorHandler");
try
{
$a=2/0;  
//这里制造一个以前无法截获的除0错误
}
catch(Exception $e)
{
echo '错误信息:', $e->getMessage();
//显示错误,这里就可以看到错误级别和错误信息了“2|Division by zero”
}

2. If try If there is an exception in the code, an exception object will be thrown. If $e is captured in catch(), it will point to the exception object. Then continue to execute 1. If there is no exception in the code in try, it will execute normally.

3.$e->getMessage() gets exception information

Custom exception class:

Function: Write some methods to solve specific exceptions (Built-in classes have no processing methods)

1. Custom exception class must be a subclass of Exception (built-in class)

2. There are only constructors in the Exception class and toString() can be rewritten

3. Define the required methods

Exception rules

• Code that needs exception handling should be placed in the try code block to catch potential exceptions.
•Every try or throw block must have at least one corresponding catch block.
•Use multiple catch blocks to catch different kinds of exceptions.
•Exceptions can be re-thrown in a catch block within a try block.

The above is the detailed explanation of PHP exception handling, error reporting, and logs. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

http://www.bkjia.com/PHPjc/633087.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/633087.htmlTechArticle we often encounter in php Some errors need to be handled. Let me summarize and introduce some exception handling, error reporting, and logs in PHP. Error handling: 1. Syntax error...


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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools