PDA

View Full Version : Error notification in QT



jduran
6th August 2012, 09:30
Dear all,

I would kite to know know can I notify errors from objects of classes derived from QObjects. Searching in the net, many times I've seen that if is suggested to overload the QCoreApplication::notify() member function (http://stackoverflow.com/questions/4661883/qt-c-error-handling), but i don't like it much, I would prefer to notify errors by emiting signals. For example:



class Foo : public QObject
{
Q_OBJECT

Q_SIGNALS:
void error(QString string);

Q_SLOTS:
void do_something()
{
try
{
a = ...;
<do something>
}
catch (std::exception &e)
{
Q_EMIt error(QString::fromStdString(e.what()));
}
}


Does anyone uses this policy? How do you use it? One signal per exception type? How do you notify errors from Qt objects?

Thanks and Best Regards,
Joaquim Duran

yeye_olive
6th August 2012, 10:35
It depends on whether the component you develop is meant to be used synchronously or asynchronously.
- In the synchronous case (direct method calls that perform an operation and return a result), you can use exceptions or any other mechanism you would use in plain C++.
- In the asynchronous case (i.e. call a slot to start an operation, and expect a signal later on to let you know that it has completed), then dedicated error signals are good practice (see QAbstractSocket::error(QAbstractSocket::SocketErro r) for example). You may use one signal with a parameter like QAbstractSocket, or several (one per error type); it is up to you. Just realize that the more signals you create, the more boilerplate code (in the form of connect() statements) you need. Clearly if all you need to know about the error is just a type, using an enum like QAbstractSocket::SocketError is the easiest option.

The approach you outine in your code is quite elegant: use exceptions in your own code and convert them to signals so that they do not propagate through Qt's internals (which might cause terrible, terrible damage).

amleto
6th August 2012, 12:41
I don't like it as a general approach. You will get code bloat from lots more connect(...) statements, and also you have to connect them TO something. So now all(?) of your objects need to be able to receive error signal as well. Additionally your methods that 'throw' still have to satisfy any guarantee on return values. e.g. all code like this has to be refactored


X getX(Key k)
{
Iter it = find(k);
if (it == end)
throw exception("oops");

return *it; // oh dear, we cant return if exception is caught and signal emitted instead
// so we have to make everything return a bool...
}


You only have to reimplement notify if your code throws whilst inside event handlers (iirc).


How do you notify errors from Qt objects?
Don't know what that means. In your suggestion you are using signals slots. So use signals/slots for error signalling and receiving.