3 ms·
Maybe this makes me an odd C++ user, but in the fifteen years I've been using it, I've never actually used exceptions. I would solve his "how do you handle a fa
by munificent 13y ago
Maybe this makes me an odd C++ user, but in the fifteen years I've been using it, I've never actually used exceptions. I would solve his "how do you handle a failed constructor" problem by either:
1. Try to define classes where construction can't fail and the class is always in a valid state. This works most of the time. Failing constructors are pretty rare in my experience.
2. If it can fail, limit it to classes that can only be constructed on the heap. Encapsulate the failure code in a static method that wraps the constructor which can itself never fail. In other words:
class Foo {
public:
// Creates a new Foo or returns NULL on failure.
Foo* create() {
Bar* bar = doThingWhichMayFailAndReturnNull();
if (!bar) return NULL;
return new Foo(bar);
}
private:
Foo(Bar* bar) : bar(bar) {}
Bar* bar;
};
This way it is impossible to get a Foo that's in an invalid state, but no exception-handling is required. The caller does have to check for NULL, of course.
3. If I do want to have a class that can be stack-allocated (usually so I can use RAII) and can possibly fail, define an explicit invalid state for the class and check that. Like:
class Connection {
public:
Connection() {
connected = openConnection();
}
~Connection() {
if (connected) closeConnection();
}
// Outside code is responsible for checking this.
bool isConnected() const { return connected; }
private:
bool connected; // True if in valid state.
};
I think I generally have the same philosophy as the author. I don't like exceptions (in C++, I love them in other languages), and I really don't like broken-state objects. But that doesn't seem insurmountable to me.
- joe_the_user 13y agoIf you are using significant libraries, you may find that your library calls have the potential to raise exceptions.
- asher 13y agoWhen I worked at Yahoo, the policy was to not use C++ exceptions. We used integer return codes. We mostly followed your #1, in which constructors do no actual work. The Google coding guide, at least a few years ago, prohibited throwing C++ exceptions. So you are hardly alone in avoiding them.