出错处理

一. c语言出错处理

1. 通过函数返回值获得出错信息、通过标准C语言中的errno()和perror()函数获得错误信息

2. 可利用C标准库中的信号处理系统,利用signal()函数(判断事件发生类型)和raise()函数(产生事件),例如:

#include <signal.h>
#include <stdio.h>

void catch_function(int);

int main()
{
	if (signal(SIGINT, catch_function) == SIG_ERR)
	{
		printf("signal(SIGINT, catch_function) fail!\n");
		return 1;
	}
	printf("raise(SIGING)\n");
	if (raise(SIGINT) != 0)
	{
		printf("raise(SIGINT) faile !\n");
		return 1;
	}
	printf("return\n");

	getchar();
	return 0;
}

void catch_function(int signal)
{
	printf("catch error %d", signal);
}

3.  使用C标准库中非局部跳转函数:setjmp()和longjmp(),例如:

#include <iostream>
#include <setjmp.h>
using namespace std;

class rainbow
{
public:
	rainbow()
	{
		cout << "rainbow()" << endl;
	}
	~rainbow()
	{
		cout << "~rainbow()" << endl;
	}
};

jmp_buf kansas;

void OZ()
{
	rainbow RB;
	for (int i = 0; i <  3; i++)
	{
		cout << "there is no place like home\n";
	}
	longjmp(kansas, 47);

	cout << "cannot be print" << endl;
}

int main()
{
	if (setjmp(kansas) == 0)
	{
		cout << "tornado, witch, munchkins...\n";
		OZ();
	}
	else
	{
		cout << "Auntie em! " << "I had the strangest dream..." << endl;
	}

	getchar();

	return 0;
}

二. c++异常处理

在c++中,C的错误处理方式不太使用,因为他们不会调用对象的析构函数

1.  如果异常类存在继承关系,catch的时候应该使用引用,因为存在对象切片问题,例如:

#include <iostream>
using namespace std;

class base
{
public:
	virtual void what()
	{
		cout << "base" << endl;
	}
};

class derived : public base
{
public:
	void what()
	{
		cout << "derived" << endl;
	}
};

void f()
{
	throw derived();
}

int main()
{
	//如果是值传递,会存在对象切片问题
	try
	{
		f();
	}
	catch(base b)
	{
		b.what();
	}
	
	//需要修改为引用传递
	try{
		f();
	}
	catch(base& b)
	{
		b.what();
	}

	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值