C++ 标准库异常类

转自:http://blog.csdn.net/zhq651/article/details/8425579

exception

C++标准库异常类继承层次中的基类为exception,其定义在exception头文件中,它是C++标准库所有函数抛出异常的基类,exception的接口定义如下:

namespace std {
       class exception {
       public:
             exception() throw();   //不抛出任何异常
             exception(const exception& e) throw();
             exception& operator= (const exception& e) throw();
             virtual ~exception() throw();
             virtual const char* what() const throw(); //返回异常的描述信息
       };
}

除了exception类,C++还提供了一些派生类,用于报告程序不正常的情况,在这些预定义的类中反映的错误模型中,主要包含逻辑错误和运行时错误两大类。

逻辑错误:logic_error

逻辑错误主要包括 invalid_argument, out_of_range, length_error, domain_error。

当函数接收到无效的实参,会抛出invaild_argument异常;如果函数接收到超出期望范围的实参,会抛出out_of_range异常,等等。

namespace std {
         class logic_error: public exception {
         public:
               explicit logic_error(const string &what_arg);
         };

         class invalid_argument: public logic_error {
         public:
               explicit invalid_argument(const string &what_arg); //非法实参
	     };

         class out_of_range: public logic_error {
         public:
               explicit out_of_range(const string &what_arg); //成员越界
	     };

         class length_error: public logic_error {
         public:
               explicit length_error(const string &what_arg); //对象超长
	     };

         class domain_error: public logic_error {
         public:
               explicit domain_error(const string &what_arg); //领域错误
	     };
}

运行时错误:runtime_error

运行时错误由程序域之外的事件引发,只有在运行时才能检测,主要包括range_error, overflow_error, underflow_error。函数可以通过抛出range_error报告算术运算中的范围错误,通过抛出overflow_error报告溢出错误。

namespace std {
         class runtime_error: public exception {
         public:
               explicit runtime_error(const string &what_arg);
         };

         class range_error: public runtime_error {
         public:
               explicit range_error(const string &what_arg); //算术运算范围错误
         };

         class overflow_error: public runtime_error {
         public:
               explicit overflow_error(const string &what_arg); //上溢错误
         };

         class underflow_error: public runtime_error {
         public:
               explicit underflow_error(const string &what_arg); //下溢错误
         };
}

注:Domain and range errors are both used when dealing with mathematical functions.

C++内建的异常类

另外,在new头文件中定义了bad_alloc异常,exception也是bad_alloc的基类,用于报告new操作符不能正确分配内存的情形。当dynamic_cast失败时,程序会抛出bad_cast异常类,其也继承自exception类。

C++ 标准库异常类

原文链接: https://www.cnblogs.com/claremore/p/4713556.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 标准库异常类

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/220332

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午10:52
下一篇 2023年2月13日 上午10:53

相关推荐