C 代码中的错误处理 [英] Error handling in C code

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

问题描述

在 C 库中以一致的方式处理错误时,您认为什么是最佳实践".

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

我一直在想两种方法:

总是返回错误代码.一个典型的函数如下所示:

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);

当使用第一种方法时,可以编写这样的代码,其中错误处理检查直接放在函数调用上:

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
}

这看起来比这里的错误处理代码更好.

Which looks better than the error handling code here.

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

但是,我认为使用返回值来返回数据会使代码更具可读性,很明显,在第二个示例中,某些东西被写入了 size 变量.

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.

你对我为什么应该更喜欢这些方法中的任何一种,或者混合它们或使用其他方法有什么想法吗?我不喜欢全局错误状态,因为它往往会使库方式的多线程使用更加痛苦.

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:

  • 将所有可能的错误状态存储在一个类型定义的枚举中,并在您的库中使用它.不要只返回整数,甚至更糟,不要将整数或不同的枚举与返回码混合在一起.

  • 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 代码中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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