意外的例外

时间:2011-10-04 21:38:22

标签: c++ exception

我正在尝试使用以下代码来测试“set_unexpected()”。我希望代码会生成如下输出:

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

但是我遇到了运行时错误:“此应用程序已请求Runtime以不寻常的方式终止它。”那么,问题是什么?感谢

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;

}

1 个答案:

答案 0 :(得分:1)

Visual C ++没有正确实现异常规范。如上所述here

  

Visual C ++在实现异常规范时脱离了ANSI标准。

,特别是

  

throw(type) - 该函数可以抛出类型类型的异常。但是,在Visual C ++ .NET中,这被解释为throw(...)

另外here

  

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

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


无论如何,请记住,不同于throw()的异常规范是generally considered a bad idea,实际上新的C ++标准(C ++ 11)不赞成它们,为{noexcept引入了throw() 1}}被使用了。