VC++异常处理-应用程序无论如何都会崩溃
VC++ exception handling - app crashes anyway
以下是我在学习C++异常处理过程中编写的代码片段(使用visual studio 2010编译器)。
#include "stdafx.h"
#include <iostream>
using namespace std;
void multi_double() {
double first,second,product;
try{
cout << "Enter the first numbern";
cin >> first;
cout << "Enter the second numbern";
cin >> second;
product = first * second;
cout << product;
}
catch(...){cout << "Got an exceptional behaviour";}
}
void stud_age(){
int age;
try{
cout << "Enter student's agen";
cin >> age;
if(age < 0)
throw;
cout << endl <<age;
}
catch(...) {
cout << "Caught heren";
}
}
class Model{
public:
Model(){cout << "ctorn";}
~Model(){cout << "dtorn";}
};
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 exceptionn";
}
return 0;
}
Enable C++exception设置为Yes[/EHsc]。但当我运行应用程序时,它仍然会崩溃!带有以下信息:
问题签名:问题事件名称:APPCRASH应用程序名称:DataTypeConversations.exe应用程序版本:0.0.0.0应用程序时间戳:4fd8c3d故障模块名称:DataTypeConversations.exe故障模块版本:0.0.0.0故障模块时间戳:4fd8c3d异常代码:c0000005异常偏移:00001051
为什么控制不来抓块?!
访问违规和所有其他类型的硬件异常在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++异常处理系统不能由硬件生成(如访问违规等)异常,只能由代码通过throw exception;
生成异常。
如果您想捕获这些异常,只有在Windows中通过使用结构化异常才能实现。这与其他编译器不兼容,并且使用__try
__except
构造而不是普通的try
/catch
。
- 当回溯以零开始时,如何调试崩溃
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我的多线程作业队列崩溃
- ExtractIconEx:可以工作,但偶尔会崩溃
- 为什么引用传递会导致此崩溃(C++)
- 试图创建流或fopen时程序崩溃
- 类对象数组的问题会导致崩溃
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 为什么要增加导致崩溃的指针
- 在虚幻引擎中删除NXOpen对象时崩溃
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- Visual Studio在尝试读取resource.txt文件时崩溃
- VC++异常处理-应用程序无论如何都会崩溃