c++ - 异常处理

标签 c++ exception

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

相关文章:

C++11 动态分配可变长度多维数组

c++ - C++ 中的二维数组文字

c++ - 如何调整我的功能模板,使它们可以是 "partially specialized"?

c# - 在 c# 自定义异常处理的情况下如何调用构造函数?

java - 尝试按 },{ 分割时出现 PatternSyntaxException

c++ - 求大 n 和 k 模 m 的二项式系数

c++ - Opengl 圆形旋转

php - die()的正确使用?

Java相当于python环境错误?

java.sql.SQLException : ORA-00902: invalid datatype 异常