try{}catch{}

本文详细介绍了PHP中使用try、catch、throw关键字进行异常处理的方法,包括如何定义、抛出和捕获异常,以及如何创建自定义异常类来处理特定错误情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php


/*

检测(try)、抛出(throw)和捕获(catch)异常。一个 try 至少要有一个与之对应的 catch。定义多个 catch 可以捕获不同的对象。
PHP 会按这些 catch 被定义的顺序执行,直到完成最后一个为止。而在这些 catch 内,又可以抛出新的异常。
*/

 

 




/*
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // 从这里开始,try 代码块内的代码将不会被执行
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// 继续执行
echo 'Hello World';
*/





/*
try {
    echo 1/0;
} catch(Exception $e) {
    echo $e->getMessage();
}


*/

 

 

 

/*

 

 try{
                    $filter = ClassLoader::getInstance($obj_filter);
                    self::$_cacheStore->put($cacheKeyName, $filter);
                }catch(SystemException $e){
                    $e->message = $e->getMessage() . '[in'.__FILE__.', line:'.__LINE__.' ]';
                    throw $e;
                }

*/

 

 

 

======================================

 



class SystemException extends Exception{

    const PHP_ERROR = '100';
   
    const FRAMEWORK_ERROR = '200';
   
    const CACHE_ERROR = '300';
   
    const DB_ERROR = '400';
   
    const DAO_ERROR = '500';

    public $type;
    public $message;
   
    public $id; 

    public function SystemException($type,$message="",$id=1000) {
        $this->type = $type;
        $this->message = $message;
        $this->id = $id;
    }
}





    function get_my_uri($encode = 0, $cache = 1){
        static $retval = false;
        if ($cache && $retval !== false)
        return $retval;
        @$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        $port = $_SERVER['SERVER_PORT'];
        if ($protocol == 'http' && $port == '80')
        $port = '';
        else if ($protocol == 'https' && $port == '443')
        $port = '';
        else
        $port = ":$port";
        @$http_host  = $_SERVER['SERVER_NAME'];
        $request_uri = $_SERVER['REQUEST_URI'];
        $retval = "$protocol://$http_host$port$request_uri";
        if ($encode)
        $retval = urlencode($retval);
        return $retval;
    }

try{
    $error = 'Always throw this error';
   throw new SystemException($error);
   echo 'Never executed';
}catch(SystemException $e){
    $msg = "Error request url:" . get_my_uri();
    $msg .= "\nSystemException";
    $msg .= "\nID:". $e->id;
    $msg .= "\nTYPE:". $e->type;
    $msg .= "\nMESSAGE:" . $e->message;
    $msg .= "\n";
    echo $msg;
    // log_error($msg);
    //header_to('error.htm')

}


?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值