Php 异常处理 exception

<?php

$a = null;

//没有接收一场处理
if($a == 0) {
        throw new DbException('val is empty');
    }
    
    exit();
    
// 接收异常并处理    
try {
    if($a == 0) {
        throw new DbException('val is empty');
    }
} catch (DbException $e) {
    echo $e->showMessage(); //输出异常信息。 
} 

// 记录异常,定义不同类型异常处理
class DbException extends Exception{
    
    public function __construct ($message = '参数异常', $code = 0) {
        parent::__construct($message, $code);
    }
    
    public function showMessage() {
        $msg = $this->getMessage();
        file_put_contents('./info.txt', 
                'Exception:' . $msg . "\n file:" .  $this->getFile() . "\n line:" . $this->getLine() . "\n Trac:" . var_export($this->getTrace(), true), 
                FILE_APPEND);
    }
}

 

posted on 2015-05-05 11:17  bandbandme  阅读(258)  评论(0编辑  收藏  举报