C/C++中自定义错误信息

在程序执行过程中往往会遇到一些错误的出现,此时需要做出相应都应对方法,同时输出错误信息。每个人 都有各自的方法。比如我,直接打印一段字符串
printf("Error: Connect fail.")
亦或者临时使用,更省事打印“111”(我相信不止我这么干,虽然都知道这是不规范操作)。
今天就学到了一个非常有意思都出错信息输出。来自微信公众号strongerHuang的文章:

/* 声明出错代码 */
#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   /* Memeroy is not enough */
#define ERR_SERV_DOWN   5   /* Service down try later */
#define ERR_UNKNOW_INFO 6   /* Unknow 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 time out */

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

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

/*
 -----------------------------------
 *函数名:perror
 *功  能:打印错误信息
 *参  数:info :错误位置(函数名或者标号用于定位错误位置 )
 *返回值:无
 -----------------------------------
 */
void perror( char* info)
{
  if ( info ){
    printf("%s: %s\n", info, errmsg[errno] );
    return;
  }
  printf("Error: %s\n", errmsg[errno] );
}

那么,如何使用呢?

bool CheckPermission( char* userName )
{
  if ( strcpy(userName, "root") != 0 ){
  errno = ERR_PERMISSION_DENIED;/* 记录错误代码,非魔鬼数字 清晰易懂 */
  return (FALSE);
}

...
}

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

如此错误输出可以统一管理方便使用,有意思的一段代码哟

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值