php异常处理

最基础的异常处理

try、catch、throw

<?php
function checkNum($number){
    if($number>1){
        throw new Exception("Value must be 1 or below");
    }
    return true;
 }

try{
    checkNum(2);
    echo 'If you see this, the number is 1 or below';
 }catch(Exception $e){
    echo 'Message: ' .$e->getMessage();
}

自定义异常处理

<?php
// 异常类中只有构造函数和 __toString 类可以覆盖,其他函数都是 final 类型。
class customException extends Exception{
    public function errorMessage(){
        $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
            .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
        return $errorMsg;
    }
}

$email = "someone@example...com";

try {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
        throw new customException($email);
    }
}catch (customException $e) {
    echo $e->errorMessage();
}

多个异常

// 捕捉到其中一个异常,就不会捕捉下面的
<?php
class customException extends Exception{
    public function errorMessage(){
        $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
            .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
        return $errorMsg;
    }
}

$email = "someone@example.com";

try {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
        throw new customException($email);
    }
    if(strpos($email, "example") !== FALSE) {
        throw new Exception("$email is an example e-mail");
    }
}catch (customException $e) {
    echo $e->errorMessage();
}catch(Exception $e) {           //基类应放在最下面
    echo $e->getMessage();
}

set_exception_handler

<?php
function myException($exception){
    echo "Exception: " , $exception->getMessage();
}

set_exception_handler('myException');       //错误和异常最终都会指向这个函数

throw new Exception('Uncaught Exception occurred');
//后面的代码不执行
//输出:Exception: Uncaught Exception occurred

trigger_error

<?php
$divisor=0;
if ($divisor == 0) {
    trigger_error("Cannot divide by zero!!!!!!!!!!", E_USER_ERROR);
}
//Fatal error: Cannot divide by zero!!!!!!!!!! in F:\WWW\l.php on line 4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值