【发布时间】:2015-09-12 21:10:36
【问题描述】:
假设我在类构造函数中有这段代码:
if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
std::cerr << "Couldn't init SDL2 video" << std::endl;
std::cerr << SDL_GetError() << std::endl;
}
如何使用 try、throw、catch 代替 if、cerr 来处理错误?我应该使用检查错误的成员函数(返回 bool),然后使用 try、throw、catch 进行错误处理吗?
构造函数:
GLWindow::GLWindow(int width, int height, std::string name) {
// Init SDL Video
if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
std::cerr << "Couldn't init SDL2 video" << std::endl;
std::cerr << SDL_GetError() << std::endl;
}
// Forward compatibility
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
// Main window
glWindow = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
// Check if Main window is created
if(glWindow == NULL) {
std::cerr << "Couldn't create main window" << std::endl;
std::cerr << SDL_GetError() << std::endl;
}
// GL Context for Main Window
glContext = SDL_GL_CreateContext(glWindow);
// Check if GL Context is created
if(glContext == NULL) {
std::cerr << "Couldn't create GL context for main window" << std::endl;
std::cerr << SDL_GetError() << std::endl;
}
}
【问题讨论】:
-
不要将异常用于一般的流控制,它们用于异常情况。除非您在构造函数中,否则我看不出它们的使用在这里如何被认为是合理的。只需返回一个成功/失败值。
-
这是在构造函数中,这就是我遇到问题的原因
-
那么您应该编辑您的帖子并在其中包含该信息。我建议添加一个示例构造函数以及如何使用它来使其清晰。
-
如果出现错误,我正在尝试退出程序。有人告诉我,我可以通过 main() 中的异常处理来做到这一点(这是创建对象的地方),但我是异常处理的新手,在类中似乎有点困难。
标签: c++ class error-handling