2011-04-05 104 views
2

這是一個非常簡單的問題,它公然是我自己的newb狀態,阻止我回來。道歉。Try-Catch沒有捕捉到自定義的異常類型

爲什麼這段代碼不工作?

try 
    { 
     create_account($accountXML); 
     echo "<p>Successfully created your account.</p>"; 
     try 
     { 
      create_page($pageXML,$base64_credentials); 
      echo "<p>Successfully created your page!</p>"; 
     } 
     catch (exception $e){ echo "<p>$e</p>"; } 
    } 
    catch(exception $e) 
    { 
     echo "<p>$e</p>";   
    } 
    catch(emailInUseException $e) 
    { 
     echo "<p>Error: Email already in use. Could not create account.</p>"; 
    } 

create_account功能...

if ((!substr_count($response, "200 Account created successfully") > 0)) // If failed 
{ 
    if ((substr_count($response, "400 EmailAddressInUse") > 0)) // If email address already in use 
     { 
      throw new emailInUseException($response); 
     } 
     throw new exception("Error: Could not create account. Reason: $response"); 
} 

emailInUse捕捉似乎並不奏效:(

更新:調試啓用我收到以下錯誤: Fatal error: Class 'emailInUseException' not found

我確定這真的很明顯。謝謝你任何幫助。

+0

'emailInUse'函數是什麼? – Neal 2011-04-05 17:20:39

+1

@Neal:'emailInUse'似乎是一個自定義的異常類型。可能更好地命名爲'EmailInUseException',但我是誰來判斷? – AgentConundrum 2011-04-05 17:25:08

+0

@代理我會那樣做的! – 2011-04-05 17:27:54

回答

8
catch(emailInUse $e) 
    { 
     echo "<p>Error: Email already in use. Could not create account.</p>"; 
    } 
    catch(exception $e) 
    { 
     echo "<p>$e</p>";   
    } 

您需要更改訂單。更一般的異常需要到底,否則你的代碼只會捕獲它並在發現特定異常之前拋出異常。

+0

我切換它,它仍然沒有工作。 Bah :( – 2011-04-05 17:29:21

+2

嗯,檢查一般捕獲中捕獲的異常類型,看看它是否與你的類類型匹配,是否被捕獲? – JohnP 2011-04-05 17:32:23

+0

@Django:迴應JohnP說的話......你的' create_account'函數拋出兩種*類型的異常,所以確保你實際上捕獲了一個'emailInUse'而不是一個簡單的''exception'類型。 – AgentConundrum 2011-04-05 17:40:44