现在的位置: 首页 > 综合 > 正文

php 异常处理 简单使用

2013年08月10日 ⁄ 综合 ⁄ 共 959字 ⁄ 字号 评论关闭

1、首先php5提供了基本的异常处理类,可直接使用

<?php
class Exception
{
    protected $message = 'Unknown exception';   // 异常信息
    protected $code = 0;                        // 用户自定义异常代码
    protected $file;                            // 发生异常的文件名
    protected $line;                            // 发生异常的代码行号

    function __construct($message = null, $code = 0);

    final function getMessage();                // 返回异常信息
    final function getCode();                   // 返回异常代码
    final function getFile();                   // 返回发生异常的文件名
    final function getLine();                   // 返回发生异常的代码行号
    final function getTrace();                  // backtrace() 数组
    final function getTraceAsString();          // 已格成化成字符串的 getTrace() 信息

    /* 可重载的方法 */
    function __toString();                       // 可输出的字符串
}
?>

简单的使用如下:(通过异常,抛出错误信息)

try {
    $error = 'my error!';
    throw new Exception($error)
} catch (Exception $e) {
    echo $e->getMessage();
}

2、我们可以扩展此类,方便我们的使用

class MyException extends Exception
{
    // 重定义构造器使 message 变为必须被指定的属性
    public function __construct($message, $code = 0) {
        // 自定义的代码

        // 确保所有变量都被正确赋值
        parent::__construct($message, $code);
    }

    // 自定义字符串输出的样式
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A Custom function for this type of exception\n";
    }
}

可以根据自己的需要扩展!

抱歉!评论已关闭.