#include <stdio.h>
#include <stdlib.h>
/* this demo is aim to make check exception as a piece of cake */
#define _SUCC 0
#define _FAIL (-1)
#define LOG_ERR printf
#define CHK_ERR_NE(_FUNC, _EXP, _RET) \
do \
{ \
if (_EXP != _RET) \
{ \
LOG_ERR("func=[%s], ret=[%d], caller=[%s], file=[%s], line=[%d] ***\n", \
#_FUNC, _RET, __func__, __FILE__, __LINE__); \
goto __EXCEPTION; \
} \
} while (0)
int foo()
{
return _FAIL;
}
int main()
{
int ret = 0;
ret = foo();
CHK_ERR_NE(foo, _SUCC, ret);
printf("Hello world!\n");
return _SUCC;
__EXCEPTION:
/* log other info: parameter value, temp var value, etc. */
/* check and release resources that allocated in this function */
printf("Hello world, exception!\n");
return _FAIL;
}
#include <stdlib.h>
/* this demo is aim to make check exception as a piece of cake */
#define _SUCC 0
#define _FAIL (-1)
#define LOG_ERR printf
#define CHK_ERR_NE(_FUNC, _EXP, _RET) \
do \
{ \
if (_EXP != _RET) \
{ \
LOG_ERR("func=[%s], ret=[%d], caller=[%s], file=[%s], line=[%d] ***\n", \
#_FUNC, _RET, __func__, __FILE__, __LINE__); \
goto __EXCEPTION; \
} \
} while (0)
int foo()
{
return _FAIL;
}
int main()
{
int ret = 0;
ret = foo();
CHK_ERR_NE(foo, _SUCC, ret);
printf("Hello world!\n");
return _SUCC;
__EXCEPTION:
/* log other info: parameter value, temp var value, etc. */
/* check and release resources that allocated in this function */
printf("Hello world, exception!\n");
return _FAIL;
}
本文介绍了一种在C语言中实现简易异常处理的方法。通过宏定义和goto语句结合使用,可以在出现错误时快速回退并记录错误信息。文章提供了一个具体的例子,展示了如何在函数返回失败时跳转到异常处理块,打印错误详情。

被折叠的 条评论
为什么被折叠?



