php try{} catch{}异常处理

1.使用方法:可能出错的代码放在try里面->抛出异常->捕捉异常并处理

   Exception()是系统内置的类,可以直接使用

<?php
try{
  $a=false;  //会出错的代码
  if($a==false){
      throw new Exception("出错了..."); //将提示信息放进去
  }
} catch(Exception $e) {     //此处表示调用Exception的异常处理类,也可以自定义异常处理类
    echo $e->getMessage();  //获取提示信息
} 

注意:异常只有被抛出了,才会被捕捉,如果没有被抛出,则直接会报错,例如:

<?php 
try{
  require "test.php";   //此处会直接报错
} catch(Exception $e) {
    echo $e->getMessage();
}

只有将异常抛出才会被捕捉

<?php 
try{
  $file="test.php";
  if(file_exists($file)){
      require "test.php";   
  } else {
      throw new Exception("文件:".$file."不存在!");
  }
} catch(Exception $e) {
    echo $e->getMessage();
}

2.自己编写异常处理类,并继承Exception

<?php 
 //自定义的异常处理类 继承异常基类
 class Myexception extends Exception {
     public $_errorMessage="";
     public function __construct($str){
         $this->_errorMessage=$str;
     }
     //自定义的异常处理方法
     public function getStr(){
         return  $this->_errorMessage;
     }
 }
 try{
     $age="100";
     if($age > 60){
         throw new Myexception("年龄大于60");       //向Myexception抛出异常
     }
 } catch(Myexception $e) {                                //被捕捉
     echo $e->getStr();
 }
 

  运行结果如下

3.异常的嵌套和向上层传递

嵌套

<?php 
 //自定义的异常处理类 继承异常基类
 class Myexception extends Exception {
     public $_errorMessage="";
     public function __construct($str){
         $this->_errorMessage=$str;
     }
     //自定义的异常处理方法
     public function getStr(){
         return  $this->_errorMessage;
     }
 }
 try{
     $age="59";
     if($age > 60){
         throw new Myexception("年龄大于60");       //向Myexception抛出异常
     } else {
         throw new Exception("年龄小于60");         //向Exception抛出异常
     }
 } catch(Myexception $e) {
     echo $e->getStr();
 } catch(Exception $e) {                            //被捕捉
     echo $e->getMessage();
 }

  运行结果如下

异常向上层传递,代码如下

<?php 
 //自定义的异常处理类 继承异常基类
 class Myexception extends Exception {
     public $_errorMessage="";
     public function __construct($str){
         $this->_errorMessage=$str;
     }
     //自定义的异常处理方法
     public function getStr(){
         return  $this->_errorMessage;
     }
 }
try{
    $age="100";
    try{
        if($age>60){
            throw new Exception("年龄大于60");       //向Exception抛出异常
        }
    } catch(Exception $a){                           //被Exception捕捉
        throw new Myexception($a->getMessage());     //向Myexception抛出异常
    }
} catch (Myexception $e){                            //被Myexception捕捉
    echo $e->getStr();
}

  运行结果如下

原文地址:https://www.cnblogs.com/flyyu/p/14103819.html