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 . "
 file:" .  $this->getFile() . "
 line:" . $this->getLine() . "
 Trac:" . var_export($this->getTrace(), true), 
                FILE_APPEND);
    }
}
原文地址:https://www.cnblogs.com/bandbandme/p/4478666.html