Date
Sep. 8th, 2024
 
2024年 8月 6日

Post: PHP Primer 022 : 异常

PHP Primer 022 : 异常

Published 12:01 Jan 25, 2012.

Created by @ezra. Categorized in #Programming, and tagged as #PHP.

Source format: Markdown

Table of Content

这一篇主要介绍 PHP 5 开始支持的异常处理。

Exception 类

在 PHP 中有许多异常处理类,而这里要介绍的是它们的基类 Exception,它包含了一些基本的属性与方法。

其中,常用的属性有:

  • message: 异常信息

  • code: 异常代码

  • file: 异常所在文件名

  • line: 异常所在行数

常用的方法有:

  • getTrace: 获取异常追踪

  • getTraceAsString: 获取异常追踪(字符串)

  • getMessage: 获取异常信息

try catch

要捕获异常,还需要了解 try catch 的用法:

<?php
try{
    // 可能出现异常的代码,以及手动异常抛出
} catch (Exception $e){
    // 异常处理
}
?>

抛出异常

那么,要怎样抛出异常呢? 只需要使用 throw 关键字即可。

举个栗子:

<?php
try {
    // 抛出
    throw new Exception('wrong');
} catch(Exception $e) {
    // 捕获
    $msg = 'Error:'.$e->getMessage()."\n";
    $msg.= $e->getTraceAsString()."\n";
    $msg.= 'Line:'.$e->getLine()."\n";
    $msg.= 'File:'.$e->getFile()."\n";
    file_put_contents('error.log', $msg);
}
?>

自定义异常处理类

在某些情况下,你也可以继承 Exception 类来自定义异常处理类。

<?php
class MyException extends Exception {
    function getInfo() {
        return 'the info';
    }
}

try {
    if (/*发生异常*/) {
        throw new MyException('error');
    }
} catch (Exception $e) {
    echo $e->getInfo();
    echo $e->getMessage();
}
?>
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系