2011-03-15 40 views
1

我真的需要你的幫助...PHP:捕獲級聯中的異常。可能嗎?

我該如何捕獲級聯中的異常? 我有一個函數(A)調用另一個文件(B)中的另一個函數調用另一個文件(C)中的另一個函數。 如何獲得函數A的捕獲函數C的錯誤? 這可能嗎? 看我下面的例子......我想是最清楚的可能......

// This code is in a file (file A) that call a function of a file B 
    require_once('/User_Login.php'); 

    try 
    { 
     CREATE_NEW_User_Login(arr_Test, 'hello'); 
     return true; 
    } 
    catch(Exception $e) 
    { 
     echo $e->getMessage(); 
     return false; 
    } 
} 





// This code is in another file (file B) that call a function of a file C 
public function CREATE_NEW_User_Login($_INPUT_Array = null, $_INPUT__Password = null) 
{ 

    // Db connection... 


    require_once('/User__DBclass.php'); 
    $DBCl_User = new User($DBConn, null); 
    $DBCl_User->SET__CLASS_ATTRIBUTES_Value__by_Array($_INPUT_Array); 
    $DBCl_User->SETTER__user_pass(md5($_INPUT__Password)); 

    $this->config['mysqli']->beginTransaction(); 

    try 
    { 
     $DBCl_User->INSERT__NEW_ROW()) 
     return true; 
    } 
    catch(Exception $e) 
    { 
     echo $e->getMessage(); 
     return false; 
    } 
} 




// This code is in another file (file C) 
// In the User Class (file: User__DBclass.php) 
public function INSERT__NEW_ROW() 
{ 
    $this->config['stmt'] = $this->config['mysqli']->prepare('INSERT INTO tbl_user 
                     SET user_id = :user_id, 
                      user_name = :user_name, 
                      act_code = :act_code;'); 


    $this->config['stmt']->bindParam(':user_id', $this->user_id, PDO::PARAM_INT); 
    $this->config['stmt']->bindParam(':user_name', $this->user_name, PDO::PARAM_STR); 
    $this->config['stmt']->bindParam(':act_code', $this->act_code, PDO::PARAM_STR); 


    try 
    { 
     $this->config['stmt']->execute(); 
     $this->user_id = intval($this->config['mysqli']->lastInsertId()); 
     return $this->user_id; 
    } 
    catch(PDOException $e) 
    { 
     echo $e->getMessage(); 
     return false; 
    } 
} 

回答

1

只是不捕獲異常,在其拋出的功能。然後它會陷入你的調用函數中。

+0

PDOException不會陷入這樣一來,他混淆了異常類型,但除此之外, - 這就是問題的答案。 – Furicane 2011-03-15 16:28:36

+0

PDOException不是Exception的子類嗎? (我不是一個PHP的傢伙,所以我不知道) – 2011-03-15 16:32:21

+0

是的,我知道這種方法,但不適合我...有時我可以調用例如方法C,而無需調用方法A和B .. 。因此,我必須在方法D中再次寫入異常......例如,我認爲方法C會像其他方法那樣捕獲異常......並且在方法A中捕獲方法B的異常以及在B中趕上方法C的例外,等等......但我不知道是否有可能... – Samuele 2011-03-15 16:32:50

2

這是異常的基本組合:如果不直接捕獲異常,則將這個異常拋出到上層元素,依此類推到「根腳本」。

注意,你必須抓住異常,否則你會得到一個錯誤。

您還可以「再」從catch塊拋出一個異常,如下所示:

catch(PDOException $e) { 
    throw $e; 
} 
2

如果你想級聯例外,那麼你需要再次把他們而不是隻返回false。

您可以爲每個異常創建新的異常類型,也可以創建一個通用異常並設置相應的消息和代碼。

catch(Exception $e) 
{ 
    //do something here if you want 
    throw $e; 
} 

參考:http://php.net/manual/en/language.exceptions.php