gpt4 book ai didi

c++ - 意外异常

转载 作者:行者123 更新时间:2023-11-28 08:16:18 26 4
gpt4 key购买 nike

我正在尝试使用以下代码来测试“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++ 没有正确实现异常规范。如前所述 here ,

Visual C++ departs from the ANSI Standard in its implementation of exception specifications.

特别是

throw(type) - The function can throw an exception of type type. However, in Visual C++ .NET, this is interpreted as throw(...).

还有 here :

Function exception specifiers other than throw() are parsed but not used.

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


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

关于c++ - 意外异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7654358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com