对不起,我之前没有提供代码,由于缩进。现在,我正在提供代码。正如我前面提到的,我在示例代码中抛出了一个异常,并且我仍然有一个由代码返回的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++异常
[提供的示例代码可能会重复一个随机数,即使抛出异常(代码提供)](http://stackoverflow.com/questions/7420793/the-sample-code-provided-返回一个随机数,甚至抛出后,一个抗体) – amit
伙计,跆拳道。你已经问过这个。 –