How to find where an exception is emited with Qt ?

When an exception is thrown and not catched in a Qt application, it get catched by Qt’s event loop, and the following message is displayed in the console:

Qt has caught an exception thrown from an event handler. Throwing exceptions from an event handler is not supported in Qt. You must reimplement QApplication::notify() and catch all exceptions there. terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

In other situations, std::bad_alloc is replaced by the name of the exception. The problem is that if you now want to know where it happens in your program, the backtrace points to where the exception is rethrown by Qt’s event loop, which is not where the error happens.

I first had this problem a few days ago when implementing multi-layers support in EXR, since the exception name was specific to OpenEXR, I just grepped the code and deduce where the error occurred. But this is not very convenient when the error is generic, like std::bad_alloc which can be thrown just anywhere. And as it turned out by Qt itself in ‘qBadAlloc()’. The solution suggested by Maelcum on IRC is simply to set a breakpoint in the function __cxa_throw, which is a function of the C++ standard library that is actually doing the job when the keyword throw is used (at least with the GNU stdlib++, no idea if it is valid with other standard library implementation). And then you get a backtrace that point to the problem.

I thought I would share this tip in case, in some day, you find yourself with an uncaught exception in a Qt application.

This entry was posted in KDE, Open Source and tagged , , , . Bookmark the permalink.

3 Responses to How to find where an exception is emited with Qt ?

  1. jonner says:

    errr.. Assuming you’re using gdb, why not just use the command “catch throw”?

  2. cyrilleberger says:

    Because I didn’t knew about it :) thanks ! (so far I always had backtrace for uncaught exceptions)

  3. The User says:

    Maybe it is interesting in this context for some hackers:
    trunk/playground/libs/crashcatching shows how to integrate DrKonqi+GDB to display such exceptions.

    The User

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>