• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++异常的常用实例(C++ Exception)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请


 

本文收集了有关C++异常的常用实例,附精简代码。

关键词:C++异常  C++ Exception try/catch throw

 

  • 异常捕获:使用try/catch捕获异常。

 

 
#include <iostream> 
#include <string> 
#include <stdexcept>  
int main() {   
   std::string str("foo");      
   try {       
      str.at(10); // access element, may throw std::out_of_range   
   } catch (const std::out_of_range& e) {       
      // what() is inherited from std::exception and contains an explanatory message       
      std::cout << e.what();  
   } 
}

 

 

  • 连续多个异常捕获

 

 std::string str("foo");    
 try {     
   str.reserve(2); // reserve extra capacity, may throw std::length_error     
   str.at(10); // access element, may throw std::out_of_range 
 } catch (const std::length_error& e) {     
   std::cout << e.what(); 
 } catch (const std::out_of_range& e) {
   std::cout << e.what(); 
 } catch (const std::exception& e) {     
   std::cout << e.what(); 
 }

 

 

  • 捕获任意异常/捕获所有异常,或者叫匿名捕获异常

 

 try {
     throw 10; 
 } catch (...) {     
     std::cout << "caught an exception"; 
 }
  • 异常捕获最佳实践:抛出异常值,捕获异常值的引用,可以避免不必要的开销。

 

 try {     
 // throw new std::runtime_error("Error!");   
 // Don't do this!     
 // This creates an exception object     
 // on the heap and would require you to catch the     
 // pointer and manage the memory yourself. This can     
 // cause memory leaks!          throw std::runtime_error("Error!"); 
 } catch (const std::runtime_error& e) {     
    std::cout << e.what() << std::endl; 
 }

 

 

  • 将异常简单处理之后,继续抛出

 

try {  
     ... // some code here 
} catch (const SomeException& e) {
     std::cout << "caught an exception";
     throw; 
}
  • 自定义C++异常

 

#include <exception>  
class Except: virtual public std::exception {      
protected:
     int error_number;               ///< Error number
     int error_offset;               ///< Error offset
     std::string error_message;      ///< Error message
public:      
/** Constructor (C++ STL string, int, int).      
*  @param msg The error message      
*  @param err_num Error number      
*  @param err_off Error offset      
*/     
explicit Except(const std::string& msg, int err_num, int err_off): 
         error_number(err_num), error_offset(err_off),error_message(msg)         {}      
/** Destructor.      
*  Virtual to allow for subclassing.      
*/     
virtual ~Except() throw () {}      
/** Returns a pointer to the (constant) error description.      
*  @return A pointer to a const char*. The underlying memory      
*  is in possession of the Except object. Callers must      
*  not attempt to free the memory.      
*/     
virtual const char* what() const throw () { 
       return error_message.c_str();     
}          
/** Returns error number.      
*  @return #error_number      
*/     
virtual int getErrorNumber() const throw() {         return error_number;     }          
/**Returns error offset.      
* @return #error_offset      
*/     
virtual int getErrorOffset() const throw() {         return error_offset;     }  
}; 
  • 抛出上述自定义异常

 

try {     
   throw(Except("Couldn't do what you were expecting", -12, -34)); 
} catch (const Except& e) {     
   std::cout<<e.what() <<"
   Error number: "<<e.getErrorNumber() <<"
   Error offset: "<<e.getErrorOffset(); 
}

 


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
使用Python发送Email电子邮件发布时间:2022-05-14
下一篇:
Python Hangman猜字游戏发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap