I'm having a debate with a co-worker about throwing exceptions from constructors, and thought I would like some feedback.
Is it OK to throw exceptions from constructors, from a design point of view?
Lets say I'm wrapping a POSIX mutex in a class, it would look something like this:
class Mutex { public: Mutex() { if (pthread_mutex_init(&mutex_, 0) != 0) { throw MutexInitException(); } } ~Mutex() { pthread_mutex_destroy(&mutex_); } void lock() { if (pthread_mutex_lock(&mutex_) != 0) { throw MutexLockException(); } } void unlock() { if (pthread_mutex_unlock(&mutex_) != 0) { throw MutexUnlockException(); } } private: pthread_mutex_t mutex_; };
My question is, is this the standard way to do it? Because if the pthread mutex_init
call fails the mutex object is unusable so throwing an exception ensures that the mutex won't be created.
Should I rather create a member function init for the Mutex class and call pthread mutex_init
within which would return a bool based on pthread mutex_init
's return? This way I don't have to use exceptions for such a low level object.
Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.
Throwing exceptions in constructors in C# is fine, but a constructor should always create a valid object.
Yes, throwing an exception from the failed constructor is the standard way of doing this. Read this FAQ about Handling a constructor that fails for more information. Having a init() method will also work, but everybody who creates the object of mutex has to remember that init() has to be called. I feel it goes against the RAII principle.
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