I am working with a library that requires certain functions to be executed to initialize the library and requires that other functions be executed to perform "clean up". To be concrete, the library is OpenGL (with GLFW and GLEW), the initialization functions include glfwInit()
and glewInit()
, and the cleanup function is glfwTerminate()
. The exact library should not matter though.
In the spirit of RAII, I created a LibraryGuard
class whose constructor initializes the library and whose destructor calls the necessary cleanup functions.
The library, of course, may fail to initialize. For example, there may not be proper hardware support, dynamic libraries may be missing, etc. To handle these cases, I have defined LibraryGuard
's constructor to throw an exception if the library cannot be initialized.
The problem is that I have no idea how to actually catch this exception. The obvious
try {
LibraryGuard lg;
}
catch () {
// exit gracefully
}
will not work because LibraryGuard
's destructor is called at the end of the try
block if lg
is successfully created, which means that the library clean-up functions are called.
The only other solutions I can think of are to either 1) not catch the exception; or 2) enclose my entire main
function inside a try
block. Neither option is particularly palatable.