try catch在java和c++中是有现成实现的,但是在c语言中是买有的,下面实现是来自网络上其他人提供的宏定义方法,该方法有一定的局限性,但是也有不少启发。
下面是一段例子代码,需要使用的人可以自行修改。
#include <stdio.h>
#include <string.h>
#define BEGIN_PROC int _error_code = 0; int _error_line = 0; int _ret = 0; {
#define END_PROC }
#define CATCH_ERROR _tabError: {
#define END_ERROR }
#define COND(Condition, ErrorCode) do\
{\
if(!(Condition))\
{\
_error_code = ErrorCode;\
_error_line = __LINE__;\
goto _tabError;\
}\
}while(0)
#define THROW(errorCode) do{_error_code = errorCode; _error_line = __LINE__; goto _tabError;}while(0)
#define EXEC(Func, code) do\
{\
_ret = (Func);\
if(code != _ret)\
{\
_error_line = __LINE__;\
_error_code = _ret;\
goto _tabError;\
}\
}while(0)
#define PRINT_ERROR() printf("error occured in function:%s, line:%d, error_code:%d\n", __FUNCTION__, _error_line, _error_code)
#define RETURN() return _error_code
#define M_ok 0x000000
#define M_array_out_of_index 0x000001
#define M_MeMory_alloc_fail 0x000002
#define M_open_file_fail 0x000003
#define M_close_file_fail 0x000004
int func1(int index);
int func2(const char *filepath);
int func3(const char *filepath);
int func1(int index)
{
int a[20] = {0};
for(int i=0; i<20; i++)
a[i] = i+4;
BEGIN_PROC
COND(index >= 0 && index < 20, M_array_out_of_index);
return a[index];
END_PROC
CATCH_ERROR
PRINT_ERROR();
RETURN();
END_ERROR
}
int func2(const char *filepath)
{
BEGIN_PROC
EXEC(func3(filepath), M_ok);
return M_ok;
END_PROC
CATCH_ERROR
PRINT_ERROR();
RETURN();
END_ERROR
}
int func3(const char *filepath)
{
FILE *fp = NULL;
fp = fopen(filepath, "r");
if(fp == NULL)
return M_open_file_fail;
int ret = fclose(fp);
if(ret == 0)
return M_ok;
else
return M_close_file_fail;
}
int main()
{
int res = 0;
res = func1(10);
printf("func1 = %d\n", res);
res = func1(-11);
printf("func1 = %d\n", res);
func2("/bin/xxxx");
func2("/bin/bash");
}
编译运行结果
rt@ubuntu:~/c thouw$ ./thouw
func1 = 14
error occured in function:func1, line:51, error_code:1
func1 = 1
error occured in function:func2, line:66, error_code:3