使用回调函数在C错误处理 [英] Using callback functions for error handling in C

查看:173
本文介绍了使用回调函数在C错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想用C错误处理造成的困难..像究竟是谁做

I have been thinking about the difficulty incurred with C error handling.. like who actually does

if(printf("hello world")==-1){exit(1);}

但你不这样做,例如冗长,而且通常没有用编码打破通用标准。好吧,如果你身边有libc中的包装?像这样,你可以做这样的事情。

But you break common standards by not doing such verbose, and usually useless coding. Well what if you had a wrapper around the libc? like so you could do something like..

//main...
error_catchall(my_errors);
printf("hello world"); //this will automatically call my_errors on an error of printf
ignore=1; //this makes it so the function will return like normal and we can check error values ourself
if(fopen.... //we want to know if the file opened or not and handle it ourself.
}

int my_errors(){
   if(ignore==0){
      _exit(1); //exit if we aren't handling this error by flagging ignore
   }
return 0;
//this is called when there is an error anywhere in the libc
}
...

我正在考虑作出这样的包装,因为我综合我自己的BSD许可证的libc(所以我已经有触摸碰不得..),但我想知道别人怎么想吧..
就这其实在现实生活中工作,会比返回-1更有用?

I am considering making such a wrapper as I am synthesizing my own BSD licensed libc(so I already have to touch the untouchable..), but I would like to know what people think about it.. would this actually work in real life and be more useful than returning -1?

推荐答案

但你会怎么能够捕获错误,当它被期望?例如,我可能希望打开文件失败,并希望在code来处理它,而不是一般的错误捕手的。

But how would you be able to catch the error when it was expected? For example I might expect a file open to fail and want to deal with it in code instead of the generic error catcher.

要做到这一点,你需要每一个功能的两个版本。一个被困的错误,一个在返回的错误。

To do this you would need two versions of every function. One that trapped errors and one the returns errors.

我做了这样的事情早就不修改库。我刚刚创建的包装功能,对于没有错误检查俗称。所以,我的电话errchk_malloc检查了回报,如果分配失败引发的错误。然后我就到位内置的malloc使用这个版本的无处不在。

I did something like this long ago without modifying the library. I just created wrapper functions for common calls that did error checking. So my errchk_malloc call checked the return and raised an error if the allocation failed. Then I just used this version everywhere in place of the built in malloc.

这篇关于使用回调函数在C错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆