C++ プログラミングガイド

実行時関数と事前定義された例外の使用

標準ヘッダー <exception> には、C++ 標準に規定されたクラスおよび例外に関連する関数が含まれています。このヘッダーにアクセスできるのは、標準モードで (コンパイラのデフォルトモード、あるいはオプション -compat=5 を使用して) コンパイルする場合だけです。次に、標準ヘッダーに含まれる宣言を示します。


// 標準ヘッダー <exception>
namespace std {
    class exception {
	    exception() throw();
	    exception(const exception&) throw();
	    exception& operator=(const exception&) throw();
	    virtual ‾exception() throw();
	    virtual const char* what() const throw();
    };
    class bad_exception: public exception { ... };
    // 予期されない例外処理
    typedef void (*unexpected_handler)();
    unexpected_handler
        set_unexpected(unexpected_handler) throw();
    void unexpected();
    // 停止処理
    typedef void (*terminate_handler)();
    terminate_handler set_terminate(terminate_handler) throw();
    void terminate();
    bool uncaught_exception() throw();
}

標準クラス exception は、選択されている言語構造または C++ 標準ライブラリによって送出されるすべての例外の基底クラスです。 exception 型のオブジェクトについては、例外を生成することなく構築、コピー、破壊が可能です。仮想メンバー関数 what() は、例外を説明する文字列を返します。

C++ リリース 4.2 で使用される例外との互換性を保つため、標準モードで使用できるヘッダー <exception.h> も用意されています。このヘッダーファイルには、標準 C++ コードへの移行のために、標準の C++ の一部ではない宣言も含まれています。開発スケジュールが許す場合は、(<exception.h> ではなく <exception> を使用して) C++ 標準に準拠するようにコードを更新してください。


// 移行のために使用されるヘッダー <exception.h>
#include <exception>
#include <new>
using std::exception;
using std::bad_exception;
using std::set_unexpected;
using std::unexpected;
using std::set_terminate;
using std::terminate;
typedef std::exception xmsg;
typedef std::bad_exception xunexpected;
typedef std::bad_alloc xalloc;

互換モード (オプション -compat=4) では、ヘッダー <exception> は使用できません。このモードでは、ヘッダー <exception.h> は C++ リリース 4.2 が提供するものと同じヘッダーを参照します。このヘッダーはここでは掲載していません。