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


How to handle exceptions thrown by the method in PHP 5.4?

如何处理方法抛出的异常?有必要的是,该方法没有在方法"检查"中抛出异常

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