Home Backend Development PHP Tutorial Summary of PHP error and exception handling_PHP tutorial

Summary of PHP error and exception handling_PHP tutorial

Jul 13, 2016 am 10:37 AM
php exception handling php error handling

通过日志记录功能,你可以将信息直接发送到其他日志服务器,或者发送到指定的电子邮箱(或者通过邮件网关发送),或者发送到操作系统日志等,从而可以有选择的记录和监视你的应用程序和网站的最重要的部分。
错误报告功能允许你自定义错误反馈的级别和类型,可以是简单的提示信息或者使用自定义的函数进行处理并返回信息.

为什么要使用错误处理?
1.是网站出错时对用户友好
2.更好的避免错误、调试、修复错误
3.避免一些安全风险
4.更好保证程序的健壮性
5.……
一、最简单的错误处理――die()
当我们预计有错误发生时,停止脚步的运行。比如连接数据库时:

复制代码 代码如下:

mysql_connect('localhost', 'root', '123456') or die ('连接数据库错误:'. mysql_error());

不过,简单地终止脚本并不总是恰当的方式。
二、自定义错误和错误触发器
我们创建一个错误处理专用函数,使用set_error_handler函数设置后,可以在 PHP 中发生错误时调用该函数。

1.定义错误处理函数的参数:

参数 描述
error_level 必需。为用户定义的错误规定错误报告级别。必须是一个值数。

     参见下面的表格:错误报告级别。

error_message 必需。为用户定义的错误规定错误消息。
error_file 可选。规定错误在其中发生的文件名。
error_line 可选。规定错误发生的行号。
error_context 可选。规定一个数组,包含了当错误发生时在用的每个变量以及它们的值。

2. Error basic predefined constants:
Value Constant Description Remarks
1 E_ERROR (integer) Fatal runtime error. This type of error is generally an unrecoverable situation, such as a problem caused by memory allocation. The consequence is that the script terminates and does not continue to run.
2 E_WARNING (integer) Runtime warning (non-fatal error). Only a prompt message is given, but the script does not terminate.
4 E_PARSE (integer) Compile time syntax parsing error. Parsing errors are generated only by the parser.
8 E_NOTICE (integer) Runtime notification. Indicates that the script encounters a situation that may appear as an error, but there may also be similar notifications in scripts that can run normally.
16 E_CORE_ERROR (integer) Fatal error occurred during PHP initialization startup. This error is similar to E_ERROR, but is generated by the PHP engine core. since PHP 4
32 E_CORE_WARNING(integer) Warning (non-fatal error) that occurred during PHP initialization startup. Similar to E_WARNING, but generated by the PHP engine core. since PHP 4
64 E_COMPILE_ERROR(integer) Fatal compile-time error. Similar to E_ERROR, but generated by the Zend script engine. since PHP 4
128 E_COMPILE_WARNING(integer) Compile-time warning (non-fatal error). Similar to E_WARNING, but generated by the Zend script engine. since PHP 4
256 E_USER_ERROR (integer) User-generated error message. Similar to E_ERROR, but it is generated by the user using the PHP function trigger_error() in the code. since PHP 4
512 E_USER_WARNING(integer) User-generated warning message. Similar to E_WARNING, but it is generated by the user using the PHP function trigger_error() in the code. since PHP 4
1024 E_USER_NOTICE(integer) Notification messages generated by users. Similar to E_NOTICE, but it is generated by the user using the PHP function trigger_error() in the code. since PHP 4
2048 E_STRICT (integer) Enable PHP's suggested modifications to your code to ensure optimal interoperability and forward compatibility. since PHP 5
4096 E_RECOVERABLE_ERROR(integer) 可被捕捉的致命错误。 它表示发生了一个可能非常危险的错误,但是还没有导致PHP引擎处于不稳定的状态。 如果该错误没有被用户自定义句柄捕获 (参见 set_error_handler()),将成为一个 E_ERROR 从而脚本会终止运行。 since PHP 5.2.0
8192 E_DEPRECATED (integer) 运行时通知。启用后将会对在未来版本中可能无法正常工作的代码给出警告。 since PHP 5.3.0
16384 E_USER_DEPRECATED(integer) 用户产少的警告信息。 类似E_DEPRECATED, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 5.3.0
30719 E_ALL (integer) E_STRICT出外的所有错误和警告信息。 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

(Levels E_ERROR and E_USER_ERROR cannot be caught by custom error handling functions) Fatal error messages cannot be caught in custom error functions because the script stops execution immediately when a fatal runtime error occurs.

3. Trigger errors
In the script where the user inputs data, it is useful to trigger an error when the user's input is invalid. In PHP, this task is accomplished by trigger_error().
You can trigger errors anywhere in the script. By adding a second parameter, you can specify the error level that is triggered.

4. Possible error types:

1).E_USER_ERROR - Fatal user-generated run-time error. The error cannot be recovered. Script execution was interrupted.
2).E_USER_WARNING - Non-fatal user-generated run-time warning. Script execution is not interrupted.
3).E_USER_NOTICE - Default. User-generated run-time notifications. The script found a possible error, which may have occurred while the script was running normally.
For example:

Copy code The code is as follows:

trigger_error("Something went wrong", E_USER_WARNING);
// Output Warning: Something went wrong in xxxx error message

3. Error reporting
By default, according to the error_log configuration in php.ini, PHP sends error records to the server's error recording system or file.
By using the error_log() function, you can send error records to a specified file or remote destination. For example, sending error messages to email is a good way.
For more error handling documentation, see: http://www.php.net/manual/zh/book.errorfunc.php

4. Exception handling
When an exception is thrown, the subsequent code will not continue to execute, and PHP will try to find a matching "catch" code block.
If the exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then a serious error (fatal error) will occur and an "Uncaught Exception" error message will be output.
1. The processing procedure 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 the 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

2. Rethrow the exception

Sometimes, when an exception is thrown, you may want to handle it differently than the standard. The exception can be thrown again in a "catch" block.
The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw the exception again with a user-friendly message.

3. Abnormal rules

1). Code that requires exception handling should be placed within a try code block to catch potential exceptions.
2). Each try or throw code block must have at least one corresponding catch code block.
3). Use multiple catch code blocks to catch different types of exceptions.
4).Exceptions can be re-thrown in the catch code block within the try code block.

In short: if an exception is thrown, you must catch it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/736790.htmlTechArticleThrough the logging function, you can send information directly to other log servers or to a specified email address ( or sent through a mail gateway), or sent to the operating system...
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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
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 Fatal error: Uncaught exception 'Exception' solution PHP Fatal error: Uncaught exception 'Exception' solution Aug 18, 2023 pm 03:28 PM

PHP is a widely used server-side programming language that provides powerful and dynamic capabilities to websites. However, in practice, developers may encounter a wide variety of errors and exceptions. One of the common errors is PHPFatalerror:Uncaughtexception'Exception'. In this article, we will explore the causes of this error and how to fix it. The concept of exception In PHP, exception refers to the unexpected situation encountered during the running process of the program, resulting in

What is the error handling mechanism in PHP? What is the error handling mechanism in PHP? May 12, 2023 pm 07:31 PM

PHP is a popular and powerful server-side programming language that can be used to develop various web applications. Just like other programming languages, PHP is prone to errors and exceptions. These errors and exceptions may be caused by various reasons, such as program errors, server errors, user input errors, etc. In order to ensure the running stability and reliability of the program, PHP provides a complete set of error handling mechanisms. The basic idea of ​​PHP error handling mechanism is: when an error occurs, the program will stop execution and output an error message. we can

PHP exception handling tips: How to catch and handle multiple exceptions using try...catch blocks PHP exception handling tips: How to catch and handle multiple exceptions using try...catch blocks Jul 29, 2023 pm 01:05 PM

PHP exception handling tips: How to use try...catch blocks to catch and handle multiple exceptions Introduction: In PHP application development, exception handling is a very important part. When an error or exception occurs in the code, reasonable exception handling can improve the robustness and reliability of the program. This article will introduce how to use the try...catch block to capture and handle multiple exceptions, helping developers perform more flexible and efficient exception handling. Introduction to Exception HandlingExceptions refer to errors or special situations that occur when a program is running. When an exception occurs

How to handle syntax errors in PHP How to handle syntax errors in PHP Aug 07, 2023 pm 04:46 PM

How to deal with syntax errors in PHP Introduction: When developing PHP programs, you often encounter syntax errors. Syntax errors are caused by code that violates PHP syntax rules, which causes the script to fail to execute correctly. This article will introduce some ways to deal with PHP syntax errors and provide corresponding code examples. Using the error prompt function PHP provides a rich error prompt function. These prompts can be turned on during the development process to discover and solve syntax errors in a timely manner. You can set error by

How to handle PHP file operation errors and generate corresponding error messages How to handle PHP file operation errors and generate corresponding error messages Aug 08, 2023 am 10:30 AM

How to handle PHP file operation errors and generate corresponding error messages. When using PHP to perform file operations, you may encounter various errors, such as file not found, permission errors, etc. These errors may cause the program to fail to run properly, so it is very important to handle file operation errors appropriately. This article will introduce how to handle PHP file operation errors and show how to generate corresponding error messages. 1. Error handling method uses error control operator PHP provides the error control operator "@", which can be added before executing statements that may cause errors.

How to handle PHP file path errors and generate corresponding error messages How to handle PHP file path errors and generate corresponding error messages Aug 06, 2023 am 10:12 AM

How to handle PHP file path errors and generate corresponding error messages. When developing and maintaining PHP applications, file path errors are often encountered. When a file that does not exist is referenced or an incorrect path is specified, a fatal error is thrown in PHP, causing the application to fail to run properly. In order to better debug and handle this situation, we can handle PHP file path errors in the following ways and generate corresponding error messages. Use absolute paths When referencing files, try to use absolute paths instead of relative paths.

Best practices for exception classification in PHP programs Best practices for exception classification in PHP programs Jun 06, 2023 am 08:01 AM

When writing PHP code, exception handling is an integral part of making the code more robust and maintainable. However, exception handling also needs to be used with caution, otherwise it may cause more problems. In this article, I will share some best practices for exception classification in PHP programs to help you make better use of exception handling to improve code quality. The concept of exception In PHP, exception refers to an error or unexpected situation that occurs when the program is running. Typically, exceptions cause the program to stop running and output an exception message.

How to handle errors in PHP backend function development? How to handle errors in PHP backend function development? Aug 04, 2023 pm 01:19 PM

How to handle errors in PHP backend function development? As a PHP backend developer, we often encounter various errors during the development process. Good error handling is an important factor in ensuring system stability and user experience. In this article, I will share some error handling methods and techniques on how to develop PHP back-end functions, and provide corresponding code examples. Setting the error reporting level PHP provides an error reporting level parameter that can be set to define the types of errors to be reported. Use error_repo

See all articles