unexpected()

C++例外指定を持つ関数が、 例外指定にリストされていない例外をスローすると、C++ ランタイムは、以下を行います。

  1. unexpected() 関数が呼び出されます。
  2. unexpected() 関数は、unexpected_handler によって指示された関数を呼び出します。 デフォルトでは、unexpected_handler は、関数 terminate() を指します。

unexpected_handler のデフォルト値を、関数 set_unexpected() を使用して置き換えることができます。

unexpected() はリターンできませんが、例外をスロー (または再スロー) することはできます。 関数 f() の例外指定に対する違反が生じた場合を想定してみましょう。 unexpected()f() の例外指定で許可された例外をスローすると、C++ ランタイムは、f() の呼び出しで別のハンドラーを検索します。 次の例は、このことを示しています。

#include <iostream>
using namespace std;
 
struct E {
  const char* message;
  E(const char* arg) : message(arg) { }
};
 
void my_unexpected() {
  cout << "Call to my_unexpected" << endl;
  throw E("Exception thrown from my_unexpected");
}
 
void f() throw(E) {
  cout << "In function f(), throw const char* object" << endl;
  throw("Exception, type const char*, thrown from f()");
}
 
int main() {
  set_unexpected(my_unexpected);
  try {
    f();
  }
  catch (E& e) {
    cout << "Exception in main(): " << e.message << endl;
  }
}

次に、上記の例の出力を示します。

In function f(), throw const char* object
Call to my_unexpected
Exception in main(): Exception thrown from my_unexpected
main() 関数の try ブロックは、関数 f() を呼び出します。 関数 f() は、型 const char* のオブジェクトをスローします。 しかし、f() の例外指定は、型 E のオブジェクトのみをスローすることを許可します。 関数 unexpected() が呼び出されます。関数 unexpected() は、my_unexpected() を呼び出します。 関数 my_unexpected() は、型 E のオブジェクトをスローします。 unexpected() は、f() の例外指定で許可されたオブジェクトをスローするので、 関数 main() にあるハンドラーは、その例外を処理できます。

unexpected() が、f() の例外指定で許可されたオブジェクトをスロー (または再スロー) しなかった場合は、C++ ランタイムは、2 つのことを行います。

関連参照

IBM Copyright 2003