search
HomeBackend DevelopmentPHP TutorialPHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法_php技巧

异常处理用于在指定的错误(异常)情况发生时改变脚本的正常流程。这种情况称为异常。
PHP 5 添加了类似于其它语言的异常处理模块。在 PHP 代码中所产生的异常可被 throw 语句抛出并被 catch 语句捕获。需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常。每一个 try 至少要有一个与之对应的 catch。使用多个 catch 可以捕获不同的类所产生的异常。当 try 代码块不再抛出异常或者找不到 catch 能匹配所抛出的异常时,PHP 代码就会在跳转到最后一个 catch 的后面继续执行。当然,PHP 允许在 catch 代码块内再次抛出(throw)异常。

当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 PHP 就会尝试查找第一个能与之匹配的 catch。如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 PHP 将会产生一个严重的错误,并且输出 Uncaught Exception ... (未捕获异常)的提示信息。

当异常被触发时,通常会发生
•当前代码状态被保存
•代码执行被切换到预定义的异常处理器函数
•根据情况,处理器也许会从保存的代码状态重新开始执行代码,终止脚本执行,或从代码中另外的位置继续执行脚本

一、错误、异常 等级常量表
error:不能在编译期发现的运行期错误,不如试图用 echo 输出一个未赋值的变量,这类问题往往导致程序或逻辑无法继续下去而需要中断;
exception:程序执行过程中出现意料之外的情况,逻辑上往往是行得通的,但不符合应用场景,比如接收到一个长度长错预定格式的用户命名,因此,异常主要靠编码人员做预先做判断后抛出,捕获异常后改变程序流程来处理这些情况,不必中断程序。
PHP 对于异常和错误的界定似乎不是很明显,尤其是低版本的PHP。
错误和日志记录值 常量 说明 备注
1 E_ERROR (integer)
致命的运行时错误。这类错误一般是不可恢复的情况,例如内存分配导致的问题。后果是导致脚本终止不再继续运行。
2 E_WARNING (integer)
运行时警告 (非致命错误)。仅给出提示信息,但是脚本不会终止运行。
4 E_PARSE (integer)
编译时语法解析错误。解析错误仅仅由分析器产生。
8 E_NOTICE (integer)
运行时通知。表示脚本遇到可能会表现为错误的情况,但是在可以正常运行的脚本里面也可能会有类似的通知。
16 E_CORE_ERROR(integer)
在PHP初始化启动过程中发生的致命错误。该错误类似 E_ERROR,但是是由PHP引擎核心产生的。 since PHP 4
32 E_CORE_WARNING(integer)
PHP初始化启动过程中发生的警告 (非致命错误) 。类似 E_WARNING,但是是由PHP引擎核心产生的。 since PHP 4
64 E_COMPILE_ERROR(integer)
致命编译时错误。类似E_ERROR, 但是是由Zend脚本引擎产生的。 since PHP 4
128 E_COMPILE_WARNING(integer)
编译时警告 (非致命错误)。类似 E_WARNING,但是是由Zend脚本引擎产生的。 since PHP 4
256 E_USER_ERROR(integer)
用户产生的错误信息。类似 E_ERROR, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 4
512 E_USER_WARNING(integer)
用户产生的警告信息。类似 E_WARNING, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 4
1024 E_USER_NOTICE(integer)
用户产生的通知信息。类似 E_NOTICE, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 4
2048 E_STRICT (integer)
启用 PHP 对代码的修改建议,以确保代码具有最佳的互操作性和向前兼容性。 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

二、error_reporting() 及 try-catch、thrown
error_reporting() 函数可以获取(不传参时)、设定脚本处理哪些异常(并非所有异常都需要处理,例如 E_CORE_WARNING、E_NOTICE、E_DEPRECATED 是可以忽略的),该设定将覆盖 php.ini 中 error_reporting选项定义的异常处理设定。
例如:
error_reporting(E_ALL&~E_NOTICE) ; // 除了E_NOTICE其他异常都会被触发(E_ALL&~E_NOTICE的二进制运算结果是:E_NOTICE对应位的值被设置为0)try-catch 无法在类的自动加载函数 __autoload() 内生效。
try-catch 无法用于捕获异常,无法捕获错误,例如 trigger_error() 触发的错误,异常和错误是不一样的。

复制代码 代码如下:

try{
// you codes that maybe cause an error
}catch(Exception $err){ // 这个错误对象需要声明类型, Exception 是系统默认异常处理类
echo $err->getMessage();
}

//thrown 可以抛出一个异常,如:
thrown new Exception('an error');
一个例子:
try {
if ( empty( $var1 ) ) throw new NotEmptyException();
if ( empty( $var2 ) ) throw new NotEmptyException();
if ( ! preg_match() ) throw new InvalidInputException();
$model->write();
$template->render( 'success' );
} catch ( NotEmptyException $e ) {
$template->render( 'error_empty' );
} catch ( InvalidInputException $e ) {
$template->render( 'error_preg' );
}
[/code]
Exception 类的结构:其中大部分方法都是 禁止改写的(final )
复制代码 代码如下:

Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 方法 */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = null]]] )
final public string getMessage ( void ) //异常抛出的信息
final public Exception getPrevious ( void ) //前一异常
final public int getCode ( void ) //异常代码,这是用户自定义的
final public string getFile ( void ) //发生异常的文件路劲
final public int getLine ( void ) //发生异常的行
final public array getTrace ( void ) //异常追踪信息(array)
final public string getTraceAsString ( void ) //异常追踪信息(string)
public string __toString ( void ) //试图直接 将异常对象当作字符串使用时调用子函数的返回值
final private void __clone ( void ) //克隆异常对象时调用
}

扩展异常类
try-catch 可以有多个 catch 子句,从第一个 catch 子句开始,如果子句内的 异常变量 类型匹配 thrown 语句抛出的异常类型,则该子句会被执行而不再执行其他catch子句,否则继续尝试下一个 catch 子句,由于Exception 是所有 异常类的基类,因此抛出的异常都会与他匹配 ,如果你像个根据不同异常类型使用不同的处理方法,应该将 Exception 类型的 catch 子句放到最后。
Exception 是所有异常的基类,可以根据实际需要扩展异常类,
复制代码 代码如下:

calss MyException extends Exception{
public errType = 'default';
public function __construct($errType=''){
$this->errType = $errType;
}
}
thrown new MyException (); //抛出一个异常
try{
// you codes that maybe cause an error
}catch(MyException $err){ // 这个错误对象需要声明类型
echo $err->errType();
}catch(ErrorException $err){ //ErrorException 是 PHP 5 增加的异常类,继承于 Exception
echo 'error !';
}catch(Exception $err){
redirect('/error.php');
}

你可能会在 catch 子句中判断异常的类型,或者根据 code 等信息来决定是否处理异常,如果你卸载 catch 子句的代码无法适当的处理捕获的异常,你可以在 catch 子句内继续 抛出异常。

三、Exception 异常的回调函数
复制代码 代码如下:

set_exception_handler(callback functionName) //发生 Exception 或其 子类的 异常是会调用此函数
function exceptionHandlerFun($errObj){ // Exception 异常的回调函数 只有一个参数,就是抛出的异常对象。
//.......
}

Exception 异常的回调函数并不能像 set_error_handler 的回调函数那样通过返回 true 来使异常被消除,即使回调函数处理了异常,后继代码也不会被继续执行,因此想继续执行后续代码必须使用 try-catch。
但是有一个例外:脚本结束回调函数可以被执行,抛出的异常即使没有被处理,该回调函数也是能被执行的。
register_shutdown_function(callback functionName[,argument1,argument2,...]);
例如:
复制代码 代码如下:

function shutdownfunction(){
echo 'script is end';
}

register_shutdown_function("shutdownfunction");
因为 shutdownfunction() 在脚本结束时被执行,所以 这个回调函数之内可以调用脚本中任意位置的函数,即使该函数定义在 错误抛出位置之后(函数定义是在 脚本编译期完成的)。

四、trigger_error(string errorMsg[,int user_error_type])
该函数用于主动触发一个错误: user_error_type 只能是 E_ALL、E_USER_ERROR、 E_USER_WARNING、 E_USER_NOTICE 或其组合的值。
set_error_handler(callbeck functionName[,user_error_type]); // 为 trigger_error() 设置一个回调函数来处理错误,包括系统抛出的错误和用户使用 trigger_error() 函数触发的错误。
可选参数 user_error_type :
如果设定此参数,则 trigger_error 抛出的错误类型符合 在user_error_type 的定义范围才能触发回调函数。
这个值的设置类似于 error_reporting() 函数 。
第一个参数(callbeck functionName):
一个函数名,该函数 可以有 5 个参数,其中前 2 个必选,依次是:
trigger_error 抛出的 user_error_type、trigger_error 抛出的 errorMsg、抛出错误的文件的绝对路劲、抛出错误的行号、抛出错误时的上下文环境 (一个数组,包含了trigger_error() 所在作用域内的所有变量、函数、类等数据 )
回调函数的返回值: 如果返回 false ,系统错误处理机制仍然继续抛出该错误,返回 true 或 无返回值 则消除错误。
trigger_error() 触发的错误不会被 try-catch 异常捕获语句捕获。
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
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools