意想不到的异常

unexpected exceptions

本文关键字:异常 意想不到      更新时间:2023-10-16

我试图使用以下代码来测试"set_unexpected()"。我期望代码将生成如下输出:

In function f(), throw const char* object
Call to my_unexpected
Exception in main(): Exception thrown from my_unexpected

但是我得到了一个运行时错误:"这个应用程序请求运行时以一种不寻常的方式终止它。"那么,问题是什么呢?由于

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 _tmain(int argc, _TCHAR* argv[])
{
      set_unexpected(my_unexpected);
  try {
    f();
  }
  catch (E& e) {
    cout << "Exception in main(): " << e.message << endl;
  }
    return 0;
}

Visual c++没有正确实现异常规范。如这里所述,

Visual c++在异常规范的实现上背离了ANSI标准。

,尤其是

throw(type) -函数可以抛出类型为type的异常。然而,在Visual c++ . net中,它被解释为throw(...)

也在这里:

解析throw()以外的函数异常说明符,但不使用

因此,您的terminate处理程序永远不会被调用,并且由于代码中没有const char *的处理程序,因此不会捕获异常并且应用程序异常终止。


无论如何,请记住,与throw()不同的异常规范通常被认为是一个坏主意,实际上新的c++标准(c++ 11)不赞成它们,引入noexcept来代替throw()