gpt4 book ai didi

c++ - 异常处理

转载 作者:行者123 更新时间:2023-11-28 03:46:33 24 4
gpt4 key购买 nike

抱歉,由于缩进,我之前发布时没有提供代码。现在,我正在提供代码。正如我之前提到的,我在示例代码中抛出了一个异常,我仍然有一个代码返回的 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++ 异常

最佳答案

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;
}

关于c++ - 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com