您的位置:首页 > 编程语言 > C语言/C++

try-catch 处理异常,也即 C++ 异常处理

2012-07-21 10:07 477 查看
// 注意,这是 C++ 程序,文件名为: SEH-test.cpp
#include "stdio.h"
class A
{
public:
	void f1() {}
	// 抛出 C++ 异常
	void f2() { throw 888;}
};

// 这个函数中使用了 try-catch 处理异常,也即 C++ 异常处理
void test1()
{
A a1;
A a2,a3;
	try
	{
	a2.f1();
	a3.f2();
	}
	catch(int errorcode)
	{
	printf("catch exception,error code:%d\n", errorcode);
	}
}

// 这个函数没什么改变,仍然采用 try-except 异常机制,也即 SEH 机制
void test()
{
int* p = 0x00000000; // pointer to NULL
	__try
	{
	// 这里调用 test1 函数
	test1();
	puts("in try");
		__try
		{
		puts("in try");
		// causes an access violation exception;
		// 导致一个存储异常
		*p = 13;
		puts(" 这里不会被执行到 ");
		}
		__finally
		{
		puts("in finally");
		}
	puts(" 这里也不会被执行到 ");
	}
	__except(puts("in filter 1"), 0)
	{
	puts("in except 1");
	}
}

void main()
{
puts("hello");
	__try
	{
	test();
	}
	__except(puts("in filter 2"), 1)
	{
	puts("in except 2");
	}
puts("world");
}
/*
hello
catch exception,error code:888
in try
in try
in filter 1
in filter 2
in finally
in except 2
world
Press any key to continue
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: