c语言抛出异常处理代码

矫情吗;* 2022-05-09 22:22 363阅读 0赞

try catch在java和c++中是有现成实现的,但是在c语言中是买有的,下面实现是来自网络上其他人提供的宏定义方法,该方法有一定的局限性,但是也有不少启发。

下面是一段例子代码,需要使用的人可以自行修改。

  1. #include <stdio.h>
  2. #include <string.h>
  3. #define BEGIN_PROC int _error_code = 0; int _error_line = 0; int _ret = 0; {
  4. #define END_PROC }
  5. #define CATCH_ERROR _tabError: {
  6. #define END_ERROR }
  7. #define COND(Condition, ErrorCode) do\
  8. {\
  9. if(!(Condition))\
  10. {\
  11. _error_code = ErrorCode;\
  12. _error_line = __LINE__;\
  13. goto _tabError;\
  14. }\
  15. }while(0)
  16. #define THROW(errorCode) do{_error_code = errorCode; _error_line = __LINE__; goto _tabError;}while(0)
  17. #define EXEC(Func, code) do\
  18. {\
  19. _ret = (Func);\
  20. if(code != _ret)\
  21. {\
  22. _error_line = __LINE__;\
  23. _error_code = _ret;\
  24. goto _tabError;\
  25. }\
  26. }while(0)
  27. #define PRINT_ERROR() printf("error occured in function:%s, line:%d, error_code:%d\n", __FUNCTION__, _error_line, _error_code)
  28. #define RETURN() return _error_code
  29. #define M_ok 0x000000
  30. #define M_array_out_of_index 0x000001
  31. #define M_MeMory_alloc_fail 0x000002
  32. #define M_open_file_fail 0x000003
  33. #define M_close_file_fail 0x000004
  34. int func1(int index);
  35. int func2(const char *filepath);
  36. int func3(const char *filepath);
  37. int func1(int index)
  38. {
  39. int a[20] = {0};
  40. for(int i=0; i<20; i++)
  41. a[i] = i+4;
  42. BEGIN_PROC
  43. COND(index >= 0 && index < 20, M_array_out_of_index);
  44. return a[index];
  45. END_PROC
  46. CATCH_ERROR
  47. PRINT_ERROR();
  48. RETURN();
  49. END_ERROR
  50. }
  51. int func2(const char *filepath)
  52. {
  53. BEGIN_PROC
  54. EXEC(func3(filepath), M_ok);
  55. return M_ok;
  56. END_PROC
  57. CATCH_ERROR
  58. PRINT_ERROR();
  59. RETURN();
  60. END_ERROR
  61. }
  62. int func3(const char *filepath)
  63. {
  64. FILE *fp = NULL;
  65. fp = fopen(filepath, "r");
  66. if(fp == NULL)
  67. return M_open_file_fail;
  68. int ret = fclose(fp);
  69. if(ret == 0)
  70. return M_ok;
  71. else
  72. return M_close_file_fail;
  73. }
  74. int main()
  75. {
  76. int res = 0;
  77. res = func1(10);
  78. printf("func1 = %d\n", res);
  79. res = func1(-11);
  80. printf("func1 = %d\n", res);
  81. func2("/bin/xxxx");
  82. func2("/bin/bash");
  83. }

编译运行结果

  1. rt@ubuntu:~/c thouw$ ./thouw
  2. func1 = 14
  3. error occured in function:func1, line:51, error_code:1
  4. func1 = 1
  5. error occured in function:func2, line:66, error_code:3

发表评论

表情:
评论列表 (有 0 条评论,363人围观)

还没有评论,来说两句吧...

相关阅读