Im 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, form 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 i unusable so throwing an exception ensures that the mutex won't be created.
Should I rather create a init function on the Mutex class and call pthread mutex_init there? This way i don't have to use exceptions for such a low level object.