2014-09-06 24 views
-1

如何处理方法抛出的异常?这是必要的,该方法没有抛出异常的方法“检查”如何处理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(); 
?> 

回答

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(); 
?> 
相关问题