Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions from constructors

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.

like image 935
lkristjansen Avatar asked May 01 '09 09:05

lkristjansen


People also ask

Is throwing exception from constructor accepted as a good practice?

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.

Can you throw exception in constructor C#?

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


1 Answers

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.

like image 69
Naveen Avatar answered Oct 08 '22 22:10

Naveen