對不起,我之前沒有提供代碼,由於縮進。現在,我正在提供代碼。正如我前面提到的,我在示例代碼中拋出了一個異常,並且我仍然有一個由代碼返回的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
夥計,跆拳道。你已經問過這個。 –