2011-04-05 54 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