<p>If I use <code>assert()</code> and the assertion fails then <code>assert()</code> will call <code>abort()</code>, ending the running program abruptly.  I can't afford that in my production code.  Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?</p>

[{'answer_id': 37474, 'author': 'wilhelmtell', 'author_id': 456, 'author_profile': 'https://Stackoverflow.com/users/456', 'pm_score': 6, 'selected': True, 'text': '<p>Yes, as a matter of fact there is.  You will need to write a custom assert function yourself, as C++\'s <code>assert()</code> is exactly C\'s <code>assert()</code>, with the <code>abort()</code> "feature" bundled in.  Fortunately, this is surprisingly straightforward.</p>\n\n<p><em>Assert.hh</em></p>\n\n<pre><code>template &lt;typename X, typename A&gt;\ninline void Assert(A assertion)\n{\n    if( !assertion ) throw X();\n}\n</code></pre>\n\n<p>The above function will throw an exception if a predicate doesn\'t hold.  You will then have the chance to catch the exception.  If you don\'t catch the exception, <code>terminate()</code> will be called, which will end the program similarly to <code>abort()</code>.</p>\n\n<p>You may wonder what about optimizing away the assertion when we\'re building for production.  In this case, you can define constants that will signify that you\'re building for production and then refer to the constant when you <code>Assert()</code>.</p>\n\n<p><em>debug.hh</em></p>\n\n<pre><code>#ifdef NDEBUG\n    const bool CHECK_WRONG = false;\n#else\n    const bool CHECK_WRONG = true;\n#endif\n</code></pre>\n\n<p><em>main.cc</em></p>\n\n<pre><code>#include&lt;iostream&gt;\n\nstruct Wrong { };\n\nint main()\n{\n    try {\n        Assert&lt;Wrong&gt;(!CHECK_WRONG || 2 + 2 == 5);\n        std::cout &lt;&lt; "I can go to sleep now.\\n";\n    }\n    catch( Wrong e ) {\n        std::cerr &lt;&lt; "Someone is wrong on the internet!\\n";\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>If <code>CHECK_WRONG</code> is a constant then the call to <code>Assert()</code> will be compiled away in production, even if the assertion is not a constant expression.  There is a slight disadvantage in that by referring to <code>CHECK_WRONG</code> we type a little more.  But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit.  So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds.</p>\n\n<p>The <code>Assert()</code> function is equivalent to typing</p>\n\n<pre><code>if( !assertion ) throw X();\n</code></pre>\n\n<p>but it clearly indicates the intent of the programmer:  make an assertion.  Assertions are also easier to grep for with this approach, just like plain <code>assert()</code>s.</p>\n\n<p>For more details on this technique see Bjarne Stroustrup\'s The C++ Programming Language 3e, section 24.3.7.2.</p>\n'}, {'answer_id': 37491, 'author': 'Ben Childs', 'author_id': 2925, 'author_profile': 'https://Stackoverflow.com/users/2925', 'pm_score': 3, 'selected': False, 'text': "<p>Asserts in C/C++ only run in debug builds. So this won't happen at runtime. In general asserts should mark things that if they happen indicate a bug, and generally show assumptions in your code etc. </p>\n\n<p>If you want to have code that checks for errors at runtime (in release) you should probably use exceptions rather than asserts as these are what they are designed to do. Your answer basically wraps an exception thrower in assert syntax. While this will work, there is no particular advantage to this that I can see over just throwing the exception in the first place.</p>\n"}, {'answer_id': 168611, 'author': 'indiv', 'author_id': 19719, 'author_profile': 'https://Stackoverflow.com/users/19719', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://library.gnome.org/devel/glib/unstable/glib-Warnings-and-Assertions.html" rel="noreferrer" title="glib documentation for error reporting functions">glib\'s error reporting functions</a> take the approach of continuing after an assert.  glib is the underlying platform independence library that Gnome (via GTK) uses.  Here\'s a macro that checks a precondition and prints a stack trace if the precondition fails.</p>\n\n<pre><code>#define RETURN_IF_FAIL(expr)      do {                  \\\n if (!(expr))                                           \\\n {                                                      \\\n         fprintf(stderr,                                \\\n                "file %s: line %d (%s): precondition `%s\' failed.", \\\n                __FILE__,                                           \\\n                __LINE__,                                           \\\n                __PRETTY_FUNCTION__,                                \\\n                #expr);                                             \\\n         print_stack_trace(2);                                      \\\n         return;                                                    \\\n };               } while(0)\n#define RETURN_VAL_IF_FAIL(expr, val)  do {                         \\\n if (!(expr))                                                       \\\n {                                                                  \\\n        fprintf(stderr,                                             \\\n                "file %s: line %d (%s): precondition `%s\' failed.",     \\\n                __FILE__,                                               \\\n                __LINE__,                                               \\\n                __PRETTY_FUNCTION__,                                    \\\n                #expr);                                                 \\\n         print_stack_trace(2);                                          \\\n         return val;                                                    \\\n };               } while(0)\n</code></pre>\n\n<p>Here\'s the function that prints the stack trace, written for an environment that uses the gnu toolchain (gcc):</p>\n\n<pre><code>void print_stack_trace(int fd)\n{\n    void *array[256];\n    size_t size;\n\n    size = backtrace (array, 256);\n    backtrace_symbols_fd(array, size, fd);\n}\n</code></pre>\n\n<p>This is how you\'d use the macros:</p>\n\n<pre><code>char *doSomething(char *ptr)\n{\n    RETURN_VAL_IF_FAIL(ptr != NULL, NULL);  // same as assert(ptr != NULL), but returns NULL if it fails.\n\n    if( ptr != NULL )        // Necessary if you want to define the macro only for debug builds\n    {\n       ...\n    }\n\n    return ptr;\n}\n\nvoid doSomethingElse(char *ptr)\n{\n    RETURN_IF_FAIL(ptr != NULL);\n}\n</code></pre>\n'}, {'answer_id': 270797, 'author': 'rlerallut', 'author_id': 20055, 'author_profile': 'https://Stackoverflow.com/users/20055', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s what I have my in "assert.h" (Mac OS 10.4):</p>\n\n<pre><code>#define assert(e) ((void) ((e) ? 0 : __assert (#e, __FILE__, __LINE__)))\n#define __assert(e, file, line) ((void)printf ("%s:%u: failed assertion `%s\'\\n", file, line, e), abort(), 0)\n</code></pre>\n\n<p>Based on that, replace the call to abort() by a throw( exception ). And instead of printf you can format the string into the exception\'s error message. In the end, you get something like this:</p>\n\n<pre><code>#define assert(e) ((void) ((e) ? 0 : my_assert (#e, __FILE__, __LINE__)))\n#define my_assert( e, file, line ) ( throw std::runtime_error(\\\n   std::string(file:)+boost::lexical_cast&lt;std::string&gt;(line)+": failed assertion "+e))\n</code></pre>\n\n<p>I haven\'t tried to compile it, but you get the meaning. </p>\n\n<p>Note: you\'ll need to make sure that the "exception" header is always included, as well as boost\'s (if you decide to use it for formatting the error message). But you can also make "my_assert" a function and only declare its prototype. Something like:</p>\n\n<pre><code>void my_assert( const char* e, const char* file, int line);\n</code></pre>\n\n<p>And implement it somewhere where you can freely include all the headers you require. </p>\n\n<p>Wrap it in some #ifdef DEBUG if you need it, or not if you always want to run those checks. </p>\n'}, {'answer_id': 26253587, 'author': 'najoast', 'author_id': 4120604, 'author_profile': 'https://Stackoverflow.com/users/4120604', 'pm_score': -1, 'selected': False, 'text': '<pre><code>_set_error_mode(_OUT_TO_MSGBOX);\n</code></pre>\n\n<p>believe me, this function can help you.</p>\n'}, {'answer_id': 35241293, 'author': 'Keith A. Lewis', 'author_id': 394744, 'author_profile': 'https://Stackoverflow.com/users/394744', 'pm_score': 0, 'selected': False, 'text': '<p>If you want to throw a character string with information about the assertion:\n<a href="http://xll8.codeplex.com/SourceControl/latest#xll/ensure.h" rel="nofollow">http://xll8.codeplex.com/SourceControl/latest#xll/ensure.h</a></p>\n'}]
['https://Stackoverflow.com/questions/37473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456/']