对不起,由于缩进的原因,我在之前的帖子中没有提供代码。现在,我提供了代码。正如我前面提到的,我在示例代码中抛出了一个异常,并且我仍然有一个由代码返回的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++异常
发布于 2011-09-15 02:22:23
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;
} 如果您不想在传播后从main函数返回0,则必须自己执行此操作。
int main()
{
try {
// ...
} catch (...) {
return 1;
}
return 0;
}发布于 2011-09-15 02:29:05
您的getProductID()函数不会从所有可能的执行路径返回。因此,当函数在没有return语句的情况下退出时,您会得到随机垃圾。当找不到产品字符串时就会出现这种情况。
您的try/catch代码块是在转移注意力,因为它不会以任何方式影响代码的其余部分(异常会立即被捕获)。
两个不相关的改进建议:
std::find而不是手动循环;这样,您就可以用两行代码编写整个函数体。https://stackoverflow.com/questions/7421050
复制相似问题