抱歉,由于缩进,我之前发布时没有提供代码。现在,我正在提供代码。正如我之前提到的,我在示例代码中抛出了一个异常,我仍然有一个代码返回的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 :(得分: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;
}
答案 1 :(得分:0)
您的getProductID()
函数未从所有可能的执行路径返回。因此,当函数退出而没有return
语句时,您会得到随机垃圾。未找到产品字符串时就是这种情况。
您的try
/ catch
块是一个红色的鲱鱼,因为它不会以任何方式影响代码的其余部分(立即捕获异常)。
两个不相关的改进提示:
通过常量引用捕获异常。
使用std::find
而非手动循环;这样,您可以将整个函数体写成两行。
不要使用C风格的数组;相反,请使用std::vector
。