This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: try-catch block

At 10:56 AM 27/08/2002 +0300, Serguei I. Ivantsov wrote:

Please help me to port this code to Linux from M$ (c++)
This sort of question is a general C++ question, and probably not best sent to this list.

something_terrible_function();  // can produce any kind of exception
// ...
It is important that process must continue execution and unlock semaphore
after any exception in something_terrible_function()
The code-snippet that you pasted will work, although the exception that occurs is not propagated. This sort of thing is best handled using the 'initialization-is-acquistion' pattern described by Stroustrup (14.4 Resource Management). A more elegant solution is:

class SemaphoreLock {
SemaphoreLock() { lock_semaphore(); } throws ();
~SemaphoreLock() { unlock_semaphore(); } throws ();
// These should be disabled, unless the resource can be duplicated.
SemaphoreLock(const SemaphoreLock&);
void operator=(const SemaphoreLock&);

// ...
// Semaphore locked for the duration of the following block:
SemaphoreLock lock();
something_terrible_function(); // Can produce anything
// code continues
// ...

The constructor/destructor will take care of the semaphore. The destructor will always be invoked, even if the terrible function throws an arbitrary exception. In this situation, the exception is also propagated and can be handled at a higher level as part of the application logic.


- Andrew

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]