【发布时间】:2016-11-18 20:42:29
【问题描述】:
所以,基本上我有这个用于外部 C 库的简单包装器代码,而且在正确处理异常方面我是新手。
提前:代码两次显示相同的问题,但对于类版本可能有不同的解决方案。
#include <some_c_lib>
void setup(){
//some setup code
//init function from the C library
//with C-style return code for error handling
if(!init()){
//error: program should terminate
//because error cannot be handled
}
//some setup code
}
class myclass{
//some members
public:
myclass(){
//some construction code
//create function of the C library
//with C-style return code error handling
if(!create()){
//error: program should terminate
//because error cannot be handled
}
}
~myclass(){
//desturction code
}
};
int main(){
std::ostream log("log.txt"); //logfile as an example
setup();
myclass obj;
while(everything_is_fine()){
//main loop stuff
}
}
问题是:我不知道终止程序的最佳方法是什么。
我不想在main 中发现异常。这将是一种毫无意义和丑陋的,因为无论如何都无法处理异常。即便如此,我还是想要某种堆栈展开机制。如果我只是 exit if 块内的程序,那么例如日志文件将不会被正确销毁。我对吗?
如果我将文件放入
if中但没有在任何地方提供 try-catch 块,文件会关闭吗?构造函数出现异常如何处理?
是否有处理此类问题的最佳方法?
我希望我的问题很清楚。
感谢您的回答,祝您有美好的一天或晚上。
【问题讨论】:
标签: c++ error-handling exception-handling coding-style code-cleanup