Wikipedia says that "A piece of code is said to be exception-safe, if run-time failures within the code will not produce ill effects, such as memory leaks, garbled stored data, or invalid output. Exception-safe code must satisfy invariants placed on the code even if exceptions occur."
And it seems that we need exception handling for exception safety. Ot the other hand, exception handling is not very popular in Qt applications as long as I see.
What are your best practices in Qt to satisfy exception safety? What do you use instead of exception handling?
Qt has caught an exception thrown from an event handler. Throwing exceptions from an event handler is not supported in Qt. You must not let any exception whatsoever propagate through Qt code. If that is not possible, in Qt 5 you must at least re-implement QCoreApplication::notify() and catch all exceptions there.
To be exception-safe, a function must ensure that objects that it has allocated by using malloc or new are destroyed, and all resources such as file handles are closed or released even if an exception is thrown.
Exception safe programming is programming so that if any piece of code that might throw an exception does throw an exception, then the state of the program is not corrupted and resources are not leaked. Getting this right using traditional methods often results in complex, unappealing and brittle code.
The four levels. Any piece of code we write has one of four levels of exception safety: No guarantee, the basic guarantee, the strong guarantee anf the nothrow guarantee.
C++ has a very powerful mechanism for excpetion-safety. Destructors are run for all variables that go out of scope due to an exception. This differs from languages like Java, where exception-safety requires the programmer to get the catch
and finally
clauses right.
The C++ behavior of calling destructors works seamlessly with Qt objects on the stack. Qt classes all have destructors and none require manual cleanup. Furthermore, QSharedPointer<T>
can be used to manage heap-allocated Qt objects; when the last pointer goes out of scope the object is destroyed. This includes the case where the pointer goes out of scope due to an exception.
So, exception-safety is certainly present in Qt. It's just transparent.
Qt is (mostly) not exception safe: http://doc.qt.io/archives/4.6/exceptionsafety.html
On the other hand dealing with exceptions correctly in event driven programming is very hard, so best is to avoid them when using Qt and pass error codes.
My best practice is to not use (or at least avoid them as much as possible) C++ exceptions in Qt based code, which makes handling them a non-problem. Qt isn't really the reason for this though, I simply feel exceptions often make things unnecessarily more complicated than they should be. But it helps Qt itself is mostly exception troubles free... :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With