2011-09-14 211 views
0

对不起,我之前没有提供代码,由于缩进。现在,我正在提供代码。正如我前面提到的,我在示例代码中抛出了一个异常,并且我仍然有一个由代码返回的0。我花了一些时间试图弄清楚,但我无法得出确切的答案。异常处理

#include <stdexcept> 
#include <iostream> 
#include <string> 

using namespace std; 


class myException_Product_Not_Found: public exception 
{ 
    public: 
     virtual const char* what() const throw() 
    { 
     return "Product not found"; 
    } 

} myExcept_Prod_Not_Found; 

int getProductID(int ids[], string names[], int numProducts, string target) 
{ 

    for(int i=0; i<numProducts; i++) 
    { 
     if(names[i]==target) 
     return ids[i];   
    } 
    try 
    { 
    throw myExcept_Prod_Not_Found;  
    } 
    catch (exception& e) 
    { 
    cout<<e.what()<<endl;  
    }           
} 

int main() //sample code to test the getProductID function 
{ 
    int productIds[]={4,5,8,10,13}; 
    string products[]={"computer","flash drive","mouse","printer","camera"}; 
    cout<<getProductID(productIds, products, 5, "computer")<<endl; 
    cout<<getProductID(productIds, products, 5, "laptop")<<endl; 
    cout<<getProductID(productIds, products, 5, "printer")<<endl; 
    return 0; 
} 

C++异常

+0

[提供的示例代码可能会重复一个随机数,即使抛出异常(代码提供)](http://stackoverflow.com/questions/7420793/the-sample-code-provided-返回一个随机数,甚至抛出后,一个抗体) – amit

+0

伙计,跆拳道。你已经问过这个。 –

回答

2
try 
{ 
throw myExcept_Prod_Not_Found;  
} 
catch (exception& e) 
{ 
cout<<e.what()<<endl;  
} 

您捕捉异常,本质上说,您与印cout的消息处理它。

这将重新抛出异常,如果你想传播它。

try 
{ 
throw myExcept_Prod_Not_Found;  
} 
catch (exception& e) 
{ 
cout<<e.what()<<endl;  
throw; 
} 

如果您想在传播后不从主函数返回0,则必须自己做。

int main() 
{ 
    try { 
    // ... 
    } catch (...) { 
    return 1; 
    } 
    return 0; 
} 
+0

嗨,汤姆,添加“扔”后,我得到了我想要的,但是,我也收到了错误消息。下面是我得到的消息:“该应用程序已经请求运行时以不寻常的方式终止它,请联系应用程序的支持团队获取更多信息。” – T3000

+0

@ T3000这是预期的行为。 Windows只是告诉你(应用程序的用户)程序员(也恰好是你)以某种方式搞砸了。我不知道你想如何处理它,但我会猜测并更新我的帖子。 –

0

您的getProductID()函数不会从所有可能的执行路径中返回。所以当函数退出而没有return声明时,你会得到随机垃圾。产品字符串未找到时就是这种情况。

您的try/catch块是一个红色鲱鱼,因为它不会以任何方式影响代码的其余部分(异常立即被捕获)。改进

两个不相关的提示:

  1. 捕获例外被不断引用。

  2. 使用std::find而不是您的手动循环;这样,您可以将整个函数体写入两行。

  3. 不要使用C风格的数组;相反,使用std::vector

+0

我甚至尝试过使用一个布尔值,如果目标已经找到,布尔值的值为true,否则为false。然后,我检查布尔值的值,如果它是假的(一旦我们离开循环)然后尝试/ catch。但它并没有带我到任何地方。 – T3000

+0

@ T3000 - 这有什么关系? –

+0

好吧,我会尝试你的建议来改善我的代码。谢谢! – T3000