Search code examples
c++x11xlib

Is it safe for X's error handler to throw exceptions?


Is it safe to do something like this?

int foo(Display*, XErrorEvent*) {
  throw 0;
}
XSetErrorHandler(foo);

I won't run into any troubles?


Solution

  • An X11 error handler is a callback provided by the user and called by Xlib. Any exception thrown from an error handler will propagate through Xlib code down to user code calling Xlib (typically XNextEvent or friends).

                   foo() <C++>
                     |
           [error is detected by Xlib] <C>
                     |
              [some more Xlib code] <C>
                     |
                [some Xlib code] <C>
                     |
                 XNextEvent()  <C>                 
                     |
                   main() <C++>
    

    Since Xlib is not written in C++, the C++ runtime does not necessarily know how to do the stack unwinding of Xlib code. Even if it by sheer luck manages to do the unwinding correctly, resources such as memory allocated by Xlib prior to calling the error handler may be lost. There are no automatic destructors in C!