gpt4 book ai didi

c++ - 类内部的错误处理

转载 作者:行者123 更新时间:2023-11-30 05:41:41 25 4
gpt4 key购买 nike

假设我在类构造函数中有这段代码:

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

最佳答案

我相信你可以做这样的事情:

try {
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
throw std::runtime_error("Couldn't init 2D video");
}
}

catch(const std::runtime_error &e) {
std::cout << e.what() << std::endl;
std::cout << SDL_GetError() << std::endl;
}

关于c++ - 类内部的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31064280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com