在类内部进行错误处理

时间:2015-06-26 03:13:01

标签: c++ class error-handling

假设我在类构造函数中包含此代码:

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

2 个答案:

答案 0 :(得分:1)

我相信你可以这样做:

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

答案 1 :(得分:0)

基于评论:

  

&#34;如果出现错误,我试图退出程序。有人告诉我,我可以通过main()中的异常处理来实现这一点   对象是制作的)但我是异常处理的新手,似乎是   在课堂上更难。&#34;

我会说你可以拨打std::terminate()来退出你的计划。

例如:

#include<exception>//std::terminate() 
//the rest of your code 

//...
if(glContext == NULL) {
    std::cerr << "Couldn't create GL context for main window" << std::endl;
    std::cerr << SDL_GetError() << std::endl;
    std::terminate();//exit program on error
    //you don't have to get rid of the std::cerr calls if you don't want to 
    //because in theory you could rout them to the terminal or some error log
    //that you could use for debugging or error logging purposes
}
//...

虽然我认为这样做很可能不是处理错误的最佳方法。 Andreas DM的答案将是我认为正确方向的良好开端。

请查看本文以获取有关异常的一些信息: https://isocpp.org/wiki/faq/exceptions#ctor-exceptions