编程的修养 - 出错信息处理

完整示例

首先,定义错误代码和错误信息数组:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

// 声明出错代码
#define ERR_NO_ERROR 0      /* No error */
#define ERR_OPEN_FILE 1     /* Open file error */
#define ERR_SEND_MESG 2     /* Sending a message error */
#define ERR_BAD_ARGS 3      /* Bad arguments */
#define ERR_MEM_NONE 4      /* Memory is not enough */
#define ERR_SERV_DOWN 5     /* Service down try later */
#define ERR_UNKNOW_INFO 6   /* Unknown information */
#define ERR_SOCKET_ERR 7    /* Socket operation failed */
#define ERR_PERMISSION 8    /* Permission denied */
#define ERR_BAD_FORMAT 9    /* Bad configuration file */
#define ERR_TIME_OUT 10     /* Communication timeout */

// 声明出错信息
char* errmsg[] = {
    /* 0 */ "No error",
    /* 1 */ "Open file error",
    /* 2 */ "Failed in sending/receiving a message",
    /* 3 */ "Bad arguments",
    /* 4 */ "Memory is not enough",
    /* 5 */ "Service is down; try later",
    /* 6 */ "Unknown information",
    /* 7 */ "A socket operation has failed",
    /* 8 */ "Permission denied",
    /* 9 */ "Bad configuration file format",
    /* 10 */ "Communication timeout",
};

// 声明错误代码全局变量
long errno = ERR_NO_ERROR;

// 打印出错信息函数
void perror(const char* info) {
    if (info) {
        printf("%s: %s\n", info, errmsg[errno]);
        return;
    }
    printf("Error: %s\n", errmsg[errno]);
}

// 示例函数,演示如何设置和处理错误
bool CheckPermission(const char* userName) {
    if (strcmp(userName, "root") != 0) {
        errno = ERR_PERMISSION;
        return false;
    }
    errno = ERR_NO_ERROR;
    return true;
}

int main() {
    const char* username = "guest";

    if (!CheckPermission(username)) {
        perror("main()");
    }

    // 其他代码...

    return 0;
}

关键点说明

  1. 错误代码与错误信息的统一管理:定义错误代码和对应的错误信息数组,有利于统一错误信息的输出格式,便于维护和管理。

  2. 全局错误变量:使用全局变量 errno 来保存错误代码,使得不同函数间可以方便地传递和检查错误状态。

  3. 统一的错误输出函数:定义 perror 函数,用于输出错误信息。这样,可以保证所有错误信息的输出格式一致。

  4. 错误检查与设置:在函数中检查错误条件并设置相应的错误代码,然后在调用函数中检查返回值并输出错误信息。

通过以上方法和建议,可以实现一个既有共性又有个性的错误信息处理机制,提高代码的可维护性和可读性。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值