2012-07-11 44 views
0

以下是我在C++中学习异常处理(使用visual studio 2010编译器)的过程中编写的代码片段。VC++异常处理 - 应用程序崩溃无论如何

#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++异常设置为是[/ EHsc]。 但是当我运行该应用程序时,它仍然崩溃!具有以下信息:

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

为什么不控制来catch块?

+0

您需要使用/ EHA编译有赶上(... )也捕获处理器异常。这是一个非常糟糕的想法。 – 2012-07-11 15:30:40

回答

1

C++异常处理系统不能硬件生成(即访问冲突等)异常,只有代码通过throw exception;生成异常。

如果您想要了解这些例外情况,则只能在Windows中使用structured exceptions。这与其他编译器不兼容,并且使用__try__except构造而不是正常的try/catch

+1

SEH异常和C++异常可以融合在一起,请参阅我的答案。 – 2012-07-11 14:40:03

2

使用称为“C结构化异常处理(SEH)”的机制在Windows中处理访问冲突和所有其他类型的硬件异常。最初设计的目的是为了给C程序提供一种更加“结构化”的方式来处理异常,而不是像Posix系统中通常的signal()/ sigaction()机制。

SEH异常可将集成到C++ Exception系统中,方法是设置一个在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; 
} 
相关问题