Qt World Summit: Submit your Presentation

Class object thrown as exception

  • Hello,

    I want to throw my created class Error object and catch it. Is this valid?
    Example code:

    #include <QCoreApplication>
    #include <QDebug>
    class Error
        enum Type {
        Error() {}
        Error(Type type, const QString &item)
            : mType(type), mItem(item) {}
        Type type() const { return mType; }
        QString item() const { return mItem; }
        Type mType;
        QString mItem;
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
        try {
            throw Error(Error::TWO, "bla");
        } catch (const Error &e) {
            qDebug() << e.type() << e.item();
        return a.exec();

  • I can't see why not

  • @VRonin Thanks. I was concerned about using QString inside class Error and Error not deriving from some base exception class. Because in pure c++ people usually don't throw std::string as exception because std::string can throw exceptions as well. For that reason custom exceptions derive from std::exception.

  • If you are using mutiple threads you can use QException base class. For the rest, Qt code itself should not throw in release code except probably for the unavoidable std::bad_alloc

Log in to reply