PHP中的错误处理、异常处理机制分析

2019-04-08 13:39:07于丽

}
return true;
}
//在 "try" 代码块中触发异常
try{
checkNum(2);
//如果异常被抛出,那么下面一行代码将不会被输出
echo 'If you see this, the number is 1 or below';
}catch(Exception $e){
//捕获异常
echo 'Message: ' .$e->getMessage();
}
?>

上面代码将获得类似这样一个错误:
Message: Value must be 1 or below
例子解释:
上面的代码抛出了一个异常,并捕获了它:
创建 checkNum() 函数。它检测数字是否大于 1。如果是,则抛出一个异常。
在 "try" 代码块中调用 checkNum() 函数。
checkNum() 函数中的异常被抛出
"catch" 代码块接收到该异常,并创建一个包含异常信息的对象 ($e)。
通过从这个 exception 对象调用 $e->getMessage(),输出来自该异常的错误消息
不过,为了遵循“每个 throw 必须对应一个 catch”的原则,可以设置一个顶层的异常处理器来处理漏掉的错误。
set_exception_handler()函数可设置处理所有未捕获异常的用户定义函数

//设置一个顶级异常处理器
function myexception($e){
   echo 'this is top exception';
} //修改默认的异常处理器
set_exception_handler("myexception");
try{
  $i=5;
  if($i<10){
    throw new exception('$i must greater than 10');
  }
}catch(Exception $e){
  //处理异常
  echo $e->getMessage().'<br/>';
  //不处理异常,继续抛出
  throw new exception('errorinfo'); //也可以用throw $e 保留原错误信息;
}

创建一个自定义的异常类

class customException extends Exception{
  public function errorMessage(){
    //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg;
  }
}
//使用
try{
  throw new customException('error message');
}catch(customException $e){
  echo $e->errorMsg();
}

可以使用多个catch来返回不同情况下的错误信息

try{
  $i=5;
  if($i>0){
    throw new customException('error message');//使用自定义异常类处理
  } if($i<-10){
    throw new exception('error2');//使用系统默认异常处理
  }
}catch(customException $e){
  echo $e->getMessage();
}catch(Exception $e1){
  echo $e1->getMessage();
}

异常的规则
需要进行异常处理的代码应该放入 try 代码块内,以便捕获潜在的异常。 每个try或throw代码块必须至少拥有一个对应的 catch 代码块。 使用多个 catch 代码块可以捕获不同种类的异常。 可以在try代码内的catch 代码块中再次抛出(re-thrown)异常。 简而言之:如果抛出了异常,就必须捕获它。
相关文章 大家在看