意想不到的异常
unexpected exceptions
我试图使用以下代码来测试"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()
。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- 意想不到的异常