【问题标题】:How to handle exceptions thrown by the method in PHP 5.4?如何处理 PHP 5.4 中的方法抛出的异常?
【发布时间】:2014-09-06 09:57:43
【问题描述】:

如何处理方法抛出的异常?该方法必须在方法'check'中没有抛出异常

 <?php 
class AllAccidents 
{
  public static function check() {
    try {
        $x = 1;
        if($x) 
        throw new Exception("Value must be more than 1");

    }catch (Exception $e){
        echo "hello>>".$e->getMessage();
    }
  }
}

class Test 
{
   public function go(){
     try{
        AllAccidents::check();
     } catch (Exception $e){

     }
   }
}

$obj = new Test();
$obj->go();
?>

【问题讨论】:

    标签: php exception error-handling


    【解决方案1】:

    我已经像这样格式化了你的代码,你可以在你想抛出异常时设置你的逻辑

    <?php 
    class AllAccidents 
    {
      public static function check() {
        try {
            self::checkNum(2);
    
        }catch (Exception $e){
            echo $e->getMessage();
        }
      }
    
     public static function checkNum($number) {
        if($number>1) {
          throw new Exception("Value must be 1 or below");
        }
      return true;
     }
    }
    
    class Test 
    {
       public function go(){
         try{
            AllAccidents::check();
         } catch (Exception $e){
    
         }
       }
    }
    
    $obj = new Test();
    $obj->go();
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2016-04-03
      • 1970-01-01
      • 2021-12-22
      • 2013-03-05
      相关资源
      最近更新 更多