1-12-1 四种处理错误的经典用法

1.12-1 四种处理错误的经典用法

  • 返回值处理错误
  • errno处理错误
  • signal处理错误

  • 异常处理错误

说明:四种处理错误的做法

#include <iostream>
#include <errno.h>
#include <signal.h>
#include <exception>
using namespace std;

int func1(int status)
{
if (status == 1)
return 1;
else if (status == 2)
return 2;
else
return 3;
}

void func2()
{
fopen("", "r");
perror("Error1");
exit(1);
}

void signal_handler(int signum)
{
printf("Receive SIGINT signal, exiting...\n");
exit(signum);
}

void func3(int signum)
{
raise(signum); // 发送信号给信号处理函数
}

void func4() throw(exception)
{
throw logic_error("this is an exception");
}

int main()
{
#if 0

for (int i = 1; i <= 3; i++)
{
int res = func1(i);
switch (res)
{
case 1:
cout << "Error1" << endl;
break;
case 2:
cout << "Error2" << endl;
break;
case 3:
cout << "Error3" << endl;
break;
}
}
#endif
#if 0
func2();
#endif
#if 0
signal(SIGINT, signal_handler); // 注册信号处理函数
func3(2);
getchar();
#endif
#if 0
try
{
func4();
}
catch (const exception &e)
{
std::cerr << e.what() << '\n';
}
#endif
}