C++ 异常处理
很抱歉,由于缩进,我之前发布时没有提供代码。现在,我提供代码。正如我前面提到的,我在示例代码中抛出了一个异常,代码仍然返回一个0。我花了一些时间试图弄明白,但我无法给出确切的答案C++ 异常处理,c++,exception-handling,C++,Exception Handling,很抱歉,由于缩进,我之前发布时没有提供代码。现在,我提供代码。正如我前面提到的,我在示例代码中抛出了一个异常,代码仍然返回一个0。我花了一些时间试图弄明白,但我无法给出确切的答案 #include <stdexcept> #include <iostream> #include <string> using namespace std; class myException_Product_Not_Found: public exception
#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;
}
#包括
#包括
#包括
使用名称空间std;
未找到myException类产品:公共异常
{
公众:
虚拟常量char*what()常量throw()
{
返回“未找到产品”;
}
}未找到myExcept_Prod_;
int getProductID(int-id[],字符串名称[],int-numProducts,字符串目标)
{
对于(int i=0;i您的getProductID()
函数不会从所有可能的执行路径返回。因此,当函数在没有return
语句的情况下退出时,您会得到随机垃圾。当找不到产品字符串时就是这种情况
您的try
/catch
块是一个麻烦,因为它不会以任何方式影响代码的其余部分(异常会立即被捕获)
两个不相关的改进建议:
通过常量引用捕获异常
使用std::find
而不是手动循环;这样,您可以在两行中编写整个函数体
不要使用C样式的数组;而是使用std::vector
可能是Dude,wtf的副本。你已经问过了。嗨,Tom,在添加“throw”之后,我得到了我想要的东西,但是,我也得到了一条错误消息。下面是我得到的消息:“这个应用程序请求运行时以一种不寻常的方式终止它。请联系应用程序的支持团队以获取更多信息。”@T3000这是预期的行为。Windows只是告诉您(应用程序的用户)程序员(碰巧也是您)不知怎么搞砸了。我不知道你想怎么处理它,但我会猜测并更新我的帖子。我甚至尝试使用布尔值,如果找到目标,布尔值为真,否则为假。然后,我检查布尔值,如果它为假(一旦我们离开循环)那就试试看吧。但它并没有带我去任何地方。@T3000——这跟什么有什么关系?
try
{
throw myExcept_Prod_Not_Found;
}
catch (exception& e)
{
cout<<e.what()<<endl;
}
try
{
throw myExcept_Prod_Not_Found;
}
catch (exception& e)
{
cout<<e.what()<<endl;
throw;
}
int main()
{
try {
// ...
} catch (...) {
return 1;
}
return 0;
}