[ C++で開発 ]

C++標準例外

<exception>をインクルードすることにより、標準例外型を利用できるようになります。標準例外は、STLでも使用されており、これからのC++プログラミングでは例外の標準規範となるでしょう。

標準例外を見てみよう

exception および exception派生例外型の継承関係

標準例外のクラス階層は以下のようになっています。

名前空間 std
                                     +---------+
                                     |exception|
                                     +---------+
                                         △
                                         |
       +--------------+------------+-----+-----+---------+-------------+
       |              |            |            |         |             |
+------+------+  +----+----+ +-----+-----+ +----+---+ +---+----+ +------+------+
|bad_exception|  |bad_alloc| |logic_error| |bad_cast| |bad_type| |runtime_error|
+-------------+  +---------+ +-----------+ +--------+ +--------+ +-------------+
                                  △                                    △
                                  |                                    |
      +----------------+----------+----+---------------+               |
      |                |                |               |               |
+-----+------+ +-------+--------+ +-----+------+ +------+-----+         |
|domain_error| |invalid_argument| |length_error| |out_of_range|         |
+------------+ +----------------+ +------------+ +------------+         |
                                                                        |
                                        +---------------+---------------+
                                        |               |               |
                                  +-----+-----+ +-------+------+ +------+-------+
                                  |range_error| |overflow_error| |underflow_error|
                                  +-----------+ +--------------+ +---------------+

exception および exception派生例外型とインクルードファイル

クラス名 インクルードファイル
exception
<exception>
bad_exception
bad_alloc
<new>
bad_cast
<typeinfo>
bad_type
<typeinfo>
logic_error
<stdexcept>
domain_error
invalid_argument
length_error
out_of_range
runtime_error
<stdexcept>
range_error
overflow_error
underflow_error

exception型のインタフェース

GCC 4.1での定義例

exception

class exception {
public:
    exception() throw() {}
    virtual ~exception() throw();
    virtual const char* what() const throw();
};

logic_error

class logic_error : public exception {
    string _M_msg;
public:
    explicit logic_error(const string& __arg);
    virtual ~logic_error() throw();
    virtual const char* what() const throw();
};

invalid_argument

class invalid_argument : public logic_error {
public:
    explicit invalid_argument(const string& __arg);
};

runtime_error

class runtime_error : public exception {
    string _M_msg;
public:
    explicit runtime_error(const string& __arg);
    virtual ~runtime_error() throw();
    virtual const char* what() const throw();
};