如何处理PHP 5.4中该方法抛出的异常?

时间:2014-09-06 09:57:43

标签: php exception error-handling

如何处理方法抛出的异常?有必要该方法不会在方法中抛出异常'检查'

 <?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();
?>

1 个答案:

答案 0 :(得分: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();
?>