A code which handles the exceptions well is called an exception safe code? Is this correct?
From here: https://codereview.stackexchange.com/a/9759/11619
You use lock/unlock pairs for the mutex. This is not exception safe.
So I would create an object that will do the lock in the constructor
and unlock in the destructor then use this to lock your mutexs. This
will make your code more exception safe.
class MutexLocker
{
pthread_mutex_t& mutex;
MutextLocker(pthread_mutex_t& mutex)
: mutex(mutex)
{
pthread_mutex_lock(&mutex);
}
~MutexLocker()
{
pthread_mutex_unlock(&mutex);
}
};
In which way is the above shown code exception safe? I don’t see any exception handling over there.
Or does exception safe code mean where we can “add” the exception handling? So, the above shown code can be made exception safe by adding exception handling, but it isn’t now?
“Exception safe” is a fairly overloaded term, but I would use it to describe sections of code which can have exceptions thrown through them and still maintain certain invariants (such as – nothing changes, no resources are leaked, all objects keep a valid state).
As an example, your
void * printHello (void* threadId)function is correct (in that it always matchespthread_mutex_lock (&demoMutex)withpthread_mutex_unlock (&demoMutex)), but if someone changed the section in the middle so that it could throw an exception (for example, by setting the throw flags onstd::cout), then your code would then permanently lockdemoMutex, with no hope for it ever being released. This would constitute a bug in your program.void * printHello (void* threadId)is said to be “exception unsafe” because of this way in which bugs can easily be introduced into your program by adding exception handling to seemingly unrelated parts.Using a RAII class to manage resources a good way to go about writing exception safe code (and is the resource management style to use in C++), because it avoids the need for duplicate manual cleanup in
catch(...)blocks, and it enforces the cleanup of resources by using the type system.