[Qt-interest] Constructor initializer exceptions

Paul Floyd paulf at free.fr
Wed Feb 11 23:08:27 CET 2009


andrew.m.goth at l-3com.com wrote:
> Paul Floyd wrote:
> 
>>If you are into exception safety,
> 
> 
> Just a reminder: Qt doesn't use C++ exceptions.  But your code might,
> and you can certainly use other libraries that do.  Such as the C++
> standard library. ;^)

Well, any use of new (other than nothrow new) is liable to throw a 
std::bad_alloc exception. I'm not sure about Visual Studio, which I 
suspect by default does not enable exceptions and RTTI (and always 
ignores exception specifiers). Just about all the compilers that I've 
used on Mac and UNIX enable exceptions.

>>MyClass::MyClass(QObject* parent) try :
>>     QObject(parent),
>>     file(new QFile(this)
>>{}
>>catch (...) // or at least std::exception
>>{}
> 
> 
> I have never seen that syntax before.  Is it standard C++?  The
> following code compiles in gcc 3.4.6:

Yes, it's standard C++.

> struct foo {foo(); int x;};
> foo::foo() try: x() {} catch (...) {}
> 
> But I read that this feature isn't in MS Visual C++ 6, only 7 onwards.
> 
> http://weseetips.com/2008/06/04/how-to-catch-exceptions-from-constructor
> -initializer-list/

VC++ 6 is really, really old. Qt 4.4 only supports it for core, Phonon 
and CLucene.

> And according to this, the exception is automatically re-thrown when the
> catch block finishes, so this construct can't be used to suppress an
> exception.
> 
> http://www.cprogramming.com/tutorial/initialization-lists-c++.html

Constructors are meant to throw exceptions - there is no other way for 
them to communicate failure. In most cases, with something like 
std::bad_alloc, you're just going to want to shut down as cleanly as 
possible.

Maybe in some cases you'd want to continue with the object partially 
constructed.

So you have something like this in most cases

Y::Y() try :
   x(new X) // failure would be catastrophic
{
}
catch (std::bad_alloc &exc)
{
     // or some other custom info about Y::Y() failing
     throw MyException();
}

Or perhaps

Y::Y() : x(0)
{
    try
    {
       x = new X;
    }
    catch (...) // or whatever
    {
       // can live without x
       // or want per-member info about any exceptions
    }
}

A+
Paul
-- 
Paul Floyd                 http://paulf.free.fr




More information about the Qt-interest-old mailing list