Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception elimination in C++ constructors

Tags:

c++

exception

We have recently been faced with the problem of porting our C++ framework to an ARM platform running uClinux where the only vendor supported compiler is GCC 2.95.3. The problem we have run into is that exceptions are extremely unreliable causing everything from not being caught at all to being caught by an unrelated thread(!). This seems to be a documented bug, i.e. here and here.

After some deliberation we decided to eliminate exceptions altoghether as we have reached a point where exceptions do a lot of damage to running applications. The main concern now is how to manage cases where a constructor failed.

We have tried lazy evaluation, where each method has the ability to instantiate dynamic resources and return a status value but that means that every class method has to return a return value which makes for a lot of ifs in the code and is very annoying in methods which generally would never cause an error.

We looked into adding a static create method which returns a pointer to a created object or NULL if creation failed but that means we cannot store objects on the stack anymore, and there is still need to pass in a reference to a status value if you want to act on the actual error.

According to Google's C++ Style Guide they do not use exceptions and only do trivial work in their constructors, using an init method for non-trivial work (Doing Work in Constructors). I cannot however find anything about how they handle construction errors when using this approach.

Has anyone here tried eliminating exceptions and come up with a good solution to handling construction failure?

like image 570
David Holm Avatar asked Dec 02 '08 15:12

David Holm


People also ask

What happens if exception is thrown in constructor?

When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.

Can constructors throw exceptions C++?

Constructors should also throw C++ exceptions to signal any input parameters received outside of allowed values or range of values. Since C++ constructors do not have a return type, it is not possible to use return codes. Therefore, the best practice is for constructors to throw an exception to signal failure.

Can we throw exception from constructor in C#?

Throwing exceptions in constructors in C# is fine, but a constructor should always create a valid object.

How do you handle a constructor error in C++?

[17.8] How can I handle a constructor that fails? Throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.


1 Answers

Generally you end up with code like this for objects on the stack:

MyClassWithNoThrowConstructor foo;
if (foo.init(bar, baz, etc) != 0) {
    // error-handling code
} else {
    // phew, we got away with it. Now for the next object...
}

And this for objects on the heap. I assume you override global operator new with something that returns NULL instead of throwing, to save yourself remembering to use nothrow new everywhere:

MyClassWithNoThrowConstructor *foo = new MyClassWithNoThrowConstructor();
if (foo == NULL) {
    // out of memory handling code
} else if (foo->init(bar, baz, etc) != 0) {
    delete foo;
    // error-handling code
} else {
    // success, we can use foo
}

Obviously if you possibly can, use smart pointers to save having to remember the deletes, but if your compiler doesn't support exceptions properly, then you might have trouble getting Boost or TR1. I don't know.

You also might want to structure the logic differently, or abstract the combined new and init, to avoid deeply-nested "arrow code" whenever you're handling multiple objects, and to common-up the error-handling between the two failure cases. The above is just the basic logic in its most painstaking form.

In both cases, the constructor sets everything to default values (it can take some arguments, provided that what it does with those arguments cannot possibly fail, for instance if it just stores them). The init method can then do the real work, which might fail, and in this case returns 0 success or any other value for failure.

You probably need to enforce that every init method across your whole codebase reports errors in the same way: you do not want some returning 0 success or a negative error code, some returning 0 success or a positive error code, some returning bool, some returning an object by value that has fields explaining the fault, some setting global errno, etc.

You could perhaps take a quick look at some Symbian class API docs online. Symbian uses C++ without exceptions: it does have a mechanism called "Leave" that partially makes up for that, but it's not valid to Leave from a constructor, so you have the same basic issue in terms of designing non-failing constructors and deferring failing operations to init routines. Of course with Symbian the init routine is permitted to Leave, so the caller doesn't need the error-handling code I indicate above, but in terms of splitting work between a C++ constructor and an additional init call, it's the same.

General principles include:

  • If your constructor wants to get a value from somewhere in a way that might fail, defer that to the init and leave the value default-initialised in the ctor.
  • If your object holds a pointer, set it to null in the ctor and set it "properly" in the init.
  • If your object holds a reference, either change it to a (smart) pointer so that it can null to start with, or else make the caller pass the value into the constructor as a parameter instead of generating it in the ctor.
  • If your constructor has members of object type, then you're fine. Their ctors won't throw either, so it's perfectly OK to construct your members (and base classes) in the initializer list in the usual way.
  • Make sure you keep track of what's set and what isn't, so that the destructor works when the init fails.
  • All functions other than constructors, the destructor, and init, can assume that init has succeeded, provided you document for your class that it is not valid to call any method other than init until init has been called and succeeded.
  • You can offer multiple init functions, which unlike constructors can call each other, in the same way that for some classes you'd offer multiple constructors.
  • You can't provide implicit conversions that might fail, so if your code currently relies on implicit conversions which throw exceptions then you have to redesign. Same goes for most operator overloads, since their return types are constrained.
like image 132
Steve Jessop Avatar answered Nov 15 '22 10:11

Steve Jessop