一. 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;
}