• php 异常处理机制 例子


    从业务的角度讲,异常偏重于保护业务数据一致性,并且强调对异常业务的处理。如果代码种只是象征性地 try……catch, 然后打印一个错误,最后over。这样的异常不如不用,因为其没有提想异常思想。

    <?php
    //  合理的异常处理:
    try{
        // 可能出错的代码段
        if(出错判断1)     throw(异常1);
        if(出错判断2)     throw(异常2);
    }catch(异常1){
        //必须的补救措施
    }catch(异常2){
        // 补救措施 记录log
    }
    
    ?>
    <?php
    
    // exception 处理例子
    
    class emailException extends exception{
    }
    
    class pwdException extends exception{
    
        function __toString(){
            return "<div id=\"error\">Exception{$this->getCOde()}:
            {$this->getMessage()}
            in File:{$this->getFIle()} on line : {$this->getLine()}</div>";
        }
    }
    
    function reg($reginfo = null){
    
        // 此处抛出异常的处理顺序与后面的try...catch 的顺序要相同,不同的话会捕捉不到正确的异常,默认只捕捉到Exception
        
        if(empty($reginfo['email'])){
            throw new emailException ('blank email');
        }
        if($reginfo['pwd'] != $reginfo['repwd']){
            throw new pwdException('two pwd is not the same');
        }
        if(empty($reginfo) || isset($reginfo)){
            throw new Exception('error  params');
        }
        echo 'success';
    }
    
    try{
        reg(array('email'=>'aaa@aaa.com', 'pwd'=>'111111', 'repwd'=>'11111'));
        //reg();
    }catch(emailException $ee){
        echo $ee->getMessage();
    }catch(pwdException $ep){
        echo $ep;
        echo $PHP_EOL,'DIFF DEAL';
    }catch(Exception $e){
        echo $e->getTraceAsString();
        echo PHP_EOL, 'other exception , deal the same way';
    }
    
    
    ?>
  • 相关阅读:
    core dump的使用
    wav文件格式
    Unicode编码 【转】
    WAV格式中常见的压缩编码
    两台交换机级联端口mac地址表维护(转载)
    pthread_cond_wait()的使用方法
    makefile自动依赖[转]
    11月的第一天
    再读simpledb 之 事务管理的实现(3)
    再读simpledb 之 元数据管理(1)
  • 原文地址:https://www.cnblogs.com/zjfazc/p/2965035.html
Copyright © 2020-2023  润新知