2014-09-06 26 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(); 
?> 
相關問題