PHP异常处理

PHP异常处理

Try、throw和catch

1、Try - 使用异常的函数应该位于 "try" 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。
2、Throw - 里规定如何触发异常。每一个 "throw" 必须对应至少一个 "catch"。
3、Catch - "catch" 代码块会捕获异常,并创建一个包含异常信息的对象。

创建一个处理异常函数:

function checkNum($number){
        if($number>1){
            throw new Exception("变量值必须小于等于1");
            
        }
        return true;
    
    }
    
    //将会出错的代码放入try里
    try{
        checkNum(2);
    
    }
    //捕获异常
    catch(Exception $e)
    {
        //通过从这个 exception 对象调用 $e->getMessage(),输出来自该异常的错误消息。
        echo 'ErrorMeaasge'.$e->getMessage();
    
}

创建一个自定义的Exception类

创建一个customException类,继承了PHP和的exception的类的所有属性,比如getLine()、getFile()和getMessage()。

customException类:

class customerException extends{
        public function errorMessage(){
        
            //错误信息
            $errorMessage = '错误行号'.$this->getLine()."错误信息".this->getMessage().'in'.$this->getFile();
        
            return $errorMessage;
        }
    
    }
    
    $email = "someone@example.com";
    
    try{
        if(filter_var($email,FILTER_VARIDATE_EMAIL)===FALSE){
            //如果不是合法的邮箱地址,抛出异常
            throw new customerException($email);
        }
    }
    catch(customerException $e){
    
    echo $e->errorMessage();
    
}

重新抛出异常

<?php
        class customException extends Exception
        {
            public function errorMessage()
            {
                // 错误信息
                $errorMsg = $this->getMessage().' 不是一个合法的 E-Mail 地址。';
                return $errorMsg;
            }
        }
         
        $email = "someone@example.com";
         
        try
        {
            try
            {
                // 检测 "example" 是否在邮箱地址中
                if(strpos($email, "example") !== FALSE)
                {
                    // 如果是个不合法的邮箱地址,抛出异常
                    throw new Exception($email);
                }
            }
            catch(Exception $e)
            {
                // 重新抛出异常
                throw new customException($email);
            }
        }
        catch (customException $e)
        {
            // 显示自定义信息
            echo $e->errorMessage();
        }
?>
原文地址:https://www.cnblogs.com/liaopeng123/p/11555510.html