用C code错误处理 [英] Error handling in C code

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

问题描述

你们认为的最佳实践,当涉及到错误处理的C库以一致的方式错误。

What do you consider "best practice" when it comes to error handling errors in a consistent way in a C library.

有两种方式我一直在思考的:

There are two ways I've been thinking of:

总是返回错误code。一个典型的功能是这样的:

Always return error code. A typical function would look like this:

MYAPI_ERROR getObjectSize(MYAPIHandle h, int* returnedSize);

的始终提供一个错误指针方式:

The always provide an error pointer approach:

int getObjectSize(MYAPIHandle h, MYAPI_ERROR* returnedError);

在使用第一种方式是可以写code这样的地方的错误处理支票直接放置在函数调用:

When using the first approach it's possible to write code like this where the error handling check is directly placed on the function call:

int size;
if(getObjectSize(h, &size) != MYAPI_SUCCESS) {
  // Error handling
}

看起来比错误处理code在这里更好。

Which looks better than the error handling code here.

MYAPIError error;
int size;
size = getObjectSize(h, &error);
if(error != MYAPI_SUCCESS) {
    // Error handling
}

不过,我认为使用返回数据的返回值使得code更可读,很明显,一些在第二个例子中写到大小可变的。

However, I think using the return value for returning data makes the code more readable, It's obvious that something was written to the size variable in the second example.

你对我又何必preFER任何的办法或者是混合,或用别的什么想法?我不是全球性的错误状态的粉丝,因为它往往使多线程使用图书馆的方式更痛苦。

Do you have any ideas on why I should prefer any of those approaches or perhaps mix them or use something else? I'm not a fan of global error states since it tends to make multi threaded use of the library way more painful.

编辑:
C ++在这个具体的想法也将是有趣的,只要听到,因为它们不涉及例外,因为它不是在此刻...

C++ specific ideas on this would also be interesting to hear about as long as they are not involving exceptions since it's not an option for me at the moment...

推荐答案

我喜欢的误差返回值的方式。如果你设计的API和你想利用你的库尽可能无痛想想这些新增内容:

I like the error as return-value way. If you're designing the api and you want to make use of your library as painless as possible think about these additions:


  • 存储所有可能的错误状态在一个Typedef的枚举,并在您的lib中使用它。不要只返回整数或者更糟,拌入报税表中codeS整数或不同的枚举。

  • store all possible error-states in one typedef'ed enum and use it in your lib. Don't just return ints or even worse, mix ints or different enumerations with return-codes.

提供了错误的转换成可读的东西的人的功能。可以很简单。只是错误枚举的,为const char *出来。

provide a function that converts errors into something human readable. Can be simple. Just error-enum in, const char* out.

我知道这个想法使多线程使用有点困难,但它会很好,如果应用程序编程人员可以设置一个全局错误回调。这样他们就能够把一个断点进入回调过程中错误迫害会议。

I know this idea makes multithreaded use a bit difficult, but it would be nice if application programmer can set an global error-callback. That way they will be able to put a breakpoint into the callback during bug-hunt sessions.

希望它帮助。

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

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