PHP 异常处理类 Exception

来源:互联网 发布:知乎回答怎么添加图片 编辑:程序博客网 时间:2024/05/17 06:40

系统默认的异常处理类

/**
 * 异常处理类
 * zhangming 2014-06-12
 * PHP为异常处理提供了内置类--Exception
 * getCode()      返回传递给构造函数的代码
 * getMessage()   返回传递给构造函数的消息
 * getFile()      返回产生异常的代码文件的完整路径
 * getLine()      返回代码文件中产生异常的代码行号
 * getTrace()     返回一个包含了产生异常的代码回退路径的数组
 * getTraceAsString()  返回与getTrace()方向相同的信息,该信息将被格式化成一个字符串
 * __toString()   允许简单地显示一个Exception对象,并且给以上所有方法可以提供的信息
 */

class Exception {
    protected $message = 'Unknown Exception';  //只有继承类和本类能使用
    private $string;  //只有本类可以使用
    protected $code = 0;
    protected $file;
    protected $line;
    private $trace;
    private $pervious;
    
    //公有的  初始化类
    public function __construct($message = null, $code = 0, Exception $pervious = null);
    
    //克隆
    final private function __clone();
    
    final public function getMessage();
    final public function getCode();
    final public function getFile();
    final public function getLine();
    final public function getTrace();
    final public function getPervious();
    final public function getTraceAsString();
    
    public function __toString();
}


/**
 * define a custome exception class
 */
class MyException extends Exception {
    //初始化对象
    public function __construct($message, $code = 0, Exception $pervious = null) {
        parent::__construct($message, $code, $pervious);
    }
    //对象的自定义字符串表示形式
    public function __toString() {
        return __CLASS__ . ":[{$this->code}]:{$this->message}\n";
    }
    //
    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
        //test
        public function test() {
                echo "my china!";
        }
}

/**
 * create a class test the exception
 */
class TestException {
    //define
    public $var;
    
    const throw_none = 0;
    const throw_custom = 1;
    const throw_default = 2;
    
    function __construct($avalue = self::throw_nonw) {
        switch ($avalue){
            case self::throw_custom:
                // throw custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::throw_default:
                // throw default one.
                throw new Exception('2 is not allowed as a parameter', 6);
                break;

            default:
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }    
}

// Example 1
try {
    //$o = new TestException(TestException::throw_custom);
    $o = new TestException(TestException::throw_custom);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

0 0
原创粉丝点击