很多时候,我不得不使用多个处理错误的库或为错误定义自己的枚举。这使得很难编写可能必须处理来自不同来源的错误的函数,然后返回其自己的错误代码。例如:
int do_foo_and_bar()
{
int err;
if ((err = libfoo_do_something()) < 0) {
// return err and indication that it was caused by foo
}
if ((err = libbar_do_something()) < 0) {
// return err and indication that it was caused by bar
}
// ...
return 0;
}
我想到了两种可能的解决方案:
int translate_foo_error(int err)
,然后我将为每个错误编写自己的字符串表示形式。struct my_error
同时包含用于标识库和错误代码的枚举的。转换为字符串将委托给每个库一个适当的函数。这似乎是一个经常出现的问题,所以我很好奇,通常如何处理?似乎前者是大多数库的工作,而后者则工作量少,并且可以使用已经提供的工具。大多数教程只是向stderr打印一条消息并在出现任何错误时退出就无济于事。我宁愿每个函数都指出出了什么问题,调用者可以从中决定如何处理它。
答案是,这取决于您代码的约束。
收集到的打印件到标准错误,如果遇到致命错误,则保全。
OpenGL将设置一些可以查询的共享状态。忽略此错误通常会导致未定义的行为。
Collected有很多线程问题,程序无法修复或修复大多数错误。例如,如果某个插件依赖某个库,并且对该库的调用失败,则该插件最了解如何从该错误中恢复。冒犯该错误无济于事,因为收集的核心永远不会知道插件N + 1
另一方面,OpenGL应用程序通常负责遇到的任何错误,并且可以尝试纠正错误。例如,如果他们正在尝试编译着色器,但是对于特定的供应商或平台可能会有一个特殊的着色器。
根据程序的设计,请考虑以下事项:
GetLastError()
函数,全局状态是否存在约束?更新:
使用global state选项时,您可能会遇到以下情况:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
char* last_err = NULL;
void set_err(char* error_message) {
if(last_err)
free(last_err);
/* Make a deep copy to be safe.
* The error string might be dynamically allocated by an external library.
* We can't know for sure where it came from.
*/
last_err = strdup(error_message);
}
int can_sqrt(int a) {
if(a < 0) {
set_err("We can't take the square root of a negative number");
return 0;
}
return 1;
}
int main(int argc, char* argv[]) {
int i = 1;
for(i = 1; i < argc; i++) {
int square = atoi(argv[i]);
if(can_sqrt(square)) {
fprintf(stdout, "the square root of %d is: %.0f\n", square, sqrt(square));
} else {
fprintf(stderr, "%s\n", last_err);
}
}
return 0;
}
运行上面的程序
$ ./a.out -1 2 -4 0 -6 4
We can't take the square root of a negative number
the square root of 2 is: 1
We can't take the square root of a negative number
the square root of 0 is: 0
We can't take the square root of a negative number
the square root of 4 is: 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句