kfmfe04
kfmfe04

Reputation: 15327

How to exit gracefully from an assertion failure in a multithreaded application

In a multi-threaded application, I use the following ASSERT macro to catch coding and data errors during debug unit-testing.

#ifndef NDEBUG
#define ASSERT(condition, message) \
do { \
    if (! (condition)) { \
        std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
        << " line " << __LINE__ << ": " << message << std::endl; \
        std::exit( EXIT_FAILURE ); \
    } \
} while (false)
#else
#define ASSERT(condition, message) do { } while( false )
#endif

It essentially does what I need, except for the nasty std::exit( EXIT_FAILURE ); that seriously needs replacing. In its current form, I get double-deletes and all sorts of nastiness which obfuscates the assertion message.

How do I exit gracefully from an assertion failures in a multithreaded app?

Perhaps I should throw from the assertion and then catch + return(1) from main()? (I'm not sure the consequences of doing this, so I'm totally open to various options)

Upvotes: 4

Views: 896

Answers (1)

David Schwartz
David Schwartz

Reputation: 182829

While it's quick and dirty, _exit works perfectly on most platforms.

Upvotes: 1

Related Questions