首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异常处理

异常处理
EN

Stack Overflow用户
提问于 2011-09-15 02:18:34
回答 2查看 219关注 0票数 0

对不起,由于缩进的原因,我在之前的帖子中没有提供代码。现在,我提供了代码。正如我前面提到的,我在示例代码中抛出了一个异常,并且我仍然有一个由代码返回的0。我花了一些时间试图弄清楚,但我不能得到确切的答案。

代码语言:javascript
复制
#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++异常

EN

回答 2

Stack Overflow用户

发布于 2011-09-15 02:22:23

代码语言:javascript
复制
try 
{ 
 throw myExcept_Prod_Not_Found;    
} 
 catch (exception& e) 
{ 
 cout<<e.what()<<endl;      
} 

您正在捕获异常,本质上是说您正在使用打印到cout的消息来处理它。

如果您希望传播异常,这将重新抛出该异常。

代码语言:javascript
复制
try 
{ 
 throw myExcept_Prod_Not_Found;    
} 
 catch (exception& e) 
{ 
 cout<<e.what()<<endl;      
 throw;
} 

如果您不想在传播后从main函数返回0,则必须自己执行此操作。

代码语言:javascript
复制
int main()
{ 
  try {
    // ...
  } catch (...) {
    return 1;
  }   
  return 0; 
}
票数 2
EN

Stack Overflow用户

发布于 2011-09-15 02:29:05

您的getProductID()函数不会从所有可能的执行路径返回。因此,当函数在没有return语句的情况下退出时,您会得到随机垃圾。当找不到产品字符串时就会出现这种情况。

您的try/catch代码块是在转移注意力,因为它不会以任何方式影响代码的其余部分(异常会立即被捕获)。

两个不相关的改进建议:

  1. 通过常量引用捕获异常。
  2. 使用std::find而不是手动循环;这样,您就可以用两行代码编写整个函数体。
  3. 不使用C样式的数组,而是使用C语言样式的数组
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7421050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档