c++ - VC++ 异常处理 - 应用程序无论如何都会崩溃

标签 c++ visual-c++ exception

以下是我在学习C++异常处理(使用visual studio 2010编译器)过程中编写的代码片段。

#include "stdafx.h"
#include <iostream>
using namespace std;
void multi_double() {

double first,second,product;
try{
cout << "Enter the first number\n";
cin >> first;
cout << "Enter the second number\n";
cin >> second;
product = first * second;
cout << product;
}
catch(...){cout << "Got an exceptional behaviour";}

}
void stud_age(){
int age;
try{
cout << "Enter student's age\n";
cin >> age;
if(age < 0)
    throw;
cout << endl <<age;
}
catch(...) {
    cout << "Caught here\n";
}
}
class Model{
public:
Model(){cout << "ctor\n";}
~Model(){cout << "dtor\n";}
};
int _tmain(int argc, _TCHAR* argv[]) {
//multi_double();
//stud_age();
int a;
try{
    Model obj;
    int *p = NULL;
    *p = 0;//expecting access violation exception

}
catch(...){
    cout << "caught an exception\n";
}
return 0;
}

启用 C++ 异常设置为 Yes[/EHsc]。 但是当我运行应用程序时,它仍然崩溃了!包含以下信息:

问题签名: 问题事件名称:APPCRASH 应用程序名称:DataTypeConversions.exe 应用程序版本:0.0.0.0 应用程序时间戳:4ffd8c3d 故障模块名称:DataTypeConversions.exe 故障模块版本:0.0.0.0 故障模块时间戳:4ffd8c3d 异常代码:c0000005 异常偏移量:00001051

为什么不控制 catch block ?!

最佳答案

访问冲突和所有其他类型的硬件异常在 Windows 中使用称为“C 结构化异常处理 (SEH)”的机制进行处理。这最初旨在为 C 程序提供一种比基于 Posix 的系统中通常的 signal()/sigaction() 机制更“结构化”的异常处理方式。

SEH 异常可以集成到 C++ 异常系统中,方法是设置一个在 SEH 堆栈展开之前调用的转换器函数。新的翻译器函数只是抛出一个 C++ 异常,而 C++ 很快就可以捕获错误!

有关所有详细信息,请参阅 MSDN 中的此文档:

http://msdn.microsoft.com/de-de/library/5z4bw5h5(v=vs.80).aspx

这是一个工作示例:

#include <windows.h>
#include <iostream>
#include <eh.h>
// You need to enable the /EHa excpetion model to make this work.
// Go to 
// Project|Properties|C/C++|Code Generation|Enable C++ Exceptions
// and select "Yes with SEH Exceptions (/EHa)"

void trans_func( unsigned int u, EXCEPTION_POINTERS* pExp )
{
    // printf( "In trans_func.\n" );
    throw "Hardware exception encountered";
}

int main() 
{
    _set_se_translator(trans_func);
    try
    {
        int *p = NULL;
        *p = 0;//expecting access violation exception
    }
    catch(const char *s)
    {
        std::cout << "caught an exception:" << s << "\n";
    }
    return 0;
}

关于c++ - VC++ 异常处理 - 应用程序无论如何都会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434817/

相关文章:

c++ - 我怎样才能输出#define值

c++ - SDL_MOUSEBUTTONUP 什么时候触发?

c++ - 为什么 auto v {create()};不编译?

c - 关于Visual C++编译器的问题

Java 错误未报告的异常 IOException;必须被捕获或宣布被抛出

c++ - 创建指向结构的指针数组 - C++

c++ - 将数据转换为 C header 作为存储为二进制文件的方式

c++ - friend 模板参数相关查找

java - 局部变量变为空(Android)

c++ - 在c++异常结构中的函数声明后抛出()?