<p>I'm looking for an answer in MS VC++.</p>

<p>When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.</p>

<p>Example in pseudo code:</p>

<pre><code>FunctionB()
{
    ...
    throw e;
    ...
}

FunctionA()
{
    ...
    FunctionB()
    ...
}

try
{
    Function A()
}
catch(e)
{
    (&lt;--- breakpoint)
    ...
}
</code></pre>

<p>I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in <code>FunctionA()</code> or <code>FunctionB()</code>, or some other function. (Assuming extensive exception use and a huge version of the above example).</p>

<p>One solution to my problem is to determine and save the call stack <strong>in the exception constructor</strong> (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.</p>

<p>Is there an easier way that requires less work?  Without having to change my large code base?</p>

<p>Are there better solutions to this problem in other languages?</p>

[{'answer_id': 36087, 'author': 'Paul Tomblin', 'author_id': 3333, 'author_profile': 'https://Stackoverflow.com/users/3333', 'pm_score': 0, 'selected': False, 'text': "<p>Other languages?  Well, in Java you call e.printStackTrace();  It doesn't get much simpler than that.</p>\n"}, {'answer_id': 36091, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 1, 'selected': False, 'text': "<p>There's no standard way to do this.</p>\n\n<p>Further, the call stack must typically be recorded at the time of the exception being <em>thrown</em>; once it has been <em>caught</em> the stack has unrolled, so you no longer know what was going on at the point of being thrown.</p>\n\n<p>In VC++ on Win32/Win64, you <em>might</em> get usable-enough results by recording the value from the compiler intrinsic _ReturnAddress() and ensuring that your exception class constructor is __declspec(noinline). In conjunction with the debug symbol library, I think you could probably get the function name (and line number, if your .pdb contains it) that corresponds to the return address using SymGetLineFromAddr64.</p>\n"}, {'answer_id': 36102, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 2, 'selected': False, 'text': '<p>There is no way to find out the source of an exception <em>after</em> it\'s caught, unless you include that information when it is thrown. By the time you catch the exception, the stack is already unwound, and there\'s no way to reconstruct the stack\'s previous state.</p>\n\n<p>Your suggestion to include the stack trace in the constructor is your best bet. Yes, it costs time during construction, but you probably shouldn\'t be throwing exceptions often enough that this is a concern. Making all of your exceptions inherit from a new base may also be more than you need. You could simply have the relevant exceptions inherit (thank you, multiple inheritance), and have a separate catch for those.</p>\n\n<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/ms680650(VS.85).aspx" rel="nofollow noreferrer">StackTrace64</a> function to build the trace (I believe there are other ways as well). Check out <a href="http://www.gamedev.net/reference/articles/article2488.asp" rel="nofollow noreferrer">this article</a> for example code.</p>\n'}, {'answer_id': 36135, 'author': 'Matt Dillard', 'author_id': 863, 'author_profile': 'https://Stackoverflow.com/users/863', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s an excellent book written by John Robbins which tackles many difficult debugging questions.  The book is called <a href="https://rads.stackoverflow.com/amzn/click/com/0735615365" rel="noreferrer" rel="nofollow noreferrer">Debugging Applications for Microsoft .NET and Microsoft Windows</a>.  Despite the title, the book contains a host of information about debugging native C++ applications.</p>\n\n<p>In this book, there is a lengthy section all about how to get the call stack for exceptions that are thrown.  If I remember correctly, some of his advice involves using <em>structured exception handling</em> (SEH) instead of (or in addition to) C++ exceptions.  I really cannot recommend the book highly enough.</p>\n'}, {'answer_id': 36175, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 0, 'selected': False, 'text': '<p>In case anyone is interested, a co-worker replied to this question to me via email:</p>\n\n<p>Artem wrote: </p>\n\n<p>There is a flag to MiniDumpWriteDump() that can do better crash dumps that will allow seeing full program state, with all global variables, etc. As for call stacks, I doubt they can be better because of optimizations... unless you turn (maybe some) optimizations off.</p>\n\n<p>Also, I think disabling inline functions and whole program optimization will help quite a lot.</p>\n\n<p>In fact, there are many dump types, maybe you could choose one small enough but still having more info\n<a href="http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx</a></p>\n\n<p>Those types won\'t help with call stack though, they only affect the amount of variables you\'ll be able to see.</p>\n\n<p>I noticed some of those dump types aren\'t supported in dbghelp.dll version 5.1 that we use. We could update it to the newest, 6.9 version though, I\'ve just checked the EULA for MS Debugging Tools -- the newest dbghelp.dll is still ok to redistribute.</p>\n'}, {'answer_id': 36217, 'author': 'Jeremy', 'author_id': 3657, 'author_profile': 'https://Stackoverflow.com/users/3657', 'pm_score': 4, 'selected': False, 'text': '<p>You pointed to a breakpoint in the code.  Since you are in the debugger, you could set a breakpoint on the constructor of the exception class, or set Visual Studio debugger to break on all thrown exceptions (Debug->Exceptions Click on C++ exceptions, select thrown and uncaught options)</p>\n'}, {'answer_id': 36223, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s how I do it in C++ using GCC libraries:</p>\n\n<pre><code>#include &lt;execinfo.h&gt; // Backtrace\n#include &lt;cxxabi.h&gt; // Demangling\n\nvector&lt;Str&gt; backtrace(size_t numskip) {\n    vector&lt;Str&gt; result;\n    std::vector&lt;void*&gt; bt(100);\n    bt.resize(backtrace(&amp;(*bt.begin()), bt.size()));\n    char **btsyms = backtrace_symbols(&amp;(*bt.begin()), bt.size());\n    if (btsyms) {\n        for (size_t i = numskip; i &lt; bt.size(); i++) {\n            Aiss in(btsyms[i]);\n            int idx = 0; Astr nt, addr, mangled;\n            in &gt;&gt; idx &gt;&gt; nt &gt;&gt; addr &gt;&gt; mangled;\n            if (mangled == "start") break;\n            int status = 0;\n            char *demangled = abi::__cxa_demangle(mangled.c_str(), 0, 0, &amp;status);\n\n            Str frame = (status==0) ? Str(demangled, demangled+strlen(demangled)) : \n                                      Str(mangled.begin(), mangled.end());\n            result.push_back(frame);\n\n            free(demangled);\n        }\n        free(btsyms);\n    }\n    return result;\n}\n</code></pre>\n\n<p>Your exception\'s constructor can simply call this function and store away the stack trace. It takes the param <code>numskip</code> because I like to slice off the exception\'s constructor from my stack traces.</p>\n'}, {'answer_id': 36473, 'author': 'graham.reeds', 'author_id': 342, 'author_profile': 'https://Stackoverflow.com/users/342', 'pm_score': 0, 'selected': False, 'text': '<p>I use my own exceptions.  You can handle them quite simple - also they contain text.  I use the format:</p>\n\n<pre><code>throw Exception( "comms::serial::serial( )", "Something failed!" );\n</code></pre>\n\n<p>Also I have a second exception format:</p>\n\n<pre><code>throw Exception( "comms::serial::serial( )", ::GetLastError( ) );\n</code></pre>\n\n<p>Which is then converted from a DWORD value to the actual message using FormatMessage.  Using the where/what format will show you what happened and in what function. </p>\n'}, {'answer_id': 38521, 'author': 'Steve Steiner', 'author_id': 3892, 'author_profile': 'https://Stackoverflow.com/users/3892', 'pm_score': 1, 'selected': False, 'text': '<p>In native code you can get a shot at walking the callstack by installing a <a href="http://msdn.microsoft.com/en-us/library/ms681420.aspx" rel="nofollow noreferrer">Vectored Exception handler</a>.  VC++ implements C++ exceptions on top of SEH exceptions and a vectored exception handler is given first shot before any frame based handlers.  However be really careful, problems introduced by vectored exception handling can be difficult to diagnose.</p>\n\n<p>Also <a href="http://blogs.msdn.com/jmstall/archive/2006/05/24/avoid-vectored-exception-handler-managed-code.aspx" rel="nofollow noreferrer">Mike Stall has some warnings</a> about using it in an app that has managed code.  Finally, read <a href="http://msdn.microsoft.com/en-us/magazine/cc301714.aspx" rel="nofollow noreferrer">Matt Pietrek\'s article</a> and make sure you understand SEH and vectored exception handling before you try this. (Nothing feels quite so bad as tracking down a critical problem to code you added help track down critical problems.)</p>\n'}, {'answer_id': 46848, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 1, 'selected': False, 'text': "<p>If you're debugging from the IDE, go to Debug->Exceptions, click Thrown for C++ exceptions.</p>\n"}, {'answer_id': 60140, 'author': 'MP24', 'author_id': 6206, 'author_profile': 'https://Stackoverflow.com/users/6206', 'pm_score': 5, 'selected': True, 'text': '<p>If you are just interested in where the exception came from, you could just write a simple macro like</p>\n\n<pre><code>#define throwException(message) \\\n    {                           \\\n        std::ostringstream oss; \\\n        oss &lt;&lt; __FILE __ &lt;&lt; " " &lt;&lt; __LINE__ &lt;&lt; " "  \\\n           &lt;&lt; __FUNC__ &lt;&lt; " " &lt;&lt; message; \\\n        throw std::exception(oss.str().c_str()); \\\n    }\n</code></pre>\n\n<p>which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).</p>\n\n<p>Then throw exceptions using</p>\n\n<pre><code>throwException("An unknown enum value has been passed!");\n</code></pre>\n'}, {'answer_id': 234322, 'author': 'Mark Ransom', 'author_id': 5987, 'author_profile': 'https://Stackoverflow.com/users/5987', 'pm_score': 3, 'selected': False, 'text': "<p>Put a breakpoint in the exception object constructor.  You'll get your breakpoint before the exception is thrown.</p>\n"}, {'answer_id': 234446, 'author': 'Martin York', 'author_id': 14065, 'author_profile': 'https://Stackoverflow.com/users/14065', 'pm_score': 1, 'selected': False, 'text': '<p>I believe MSDev allows you to set break points when an exception is thrown.</p>\n\n<p>Alternatively put the break point on the constructor of your exception object.</p>\n'}, {'answer_id': 59470923, 'author': 'GPMueller', 'author_id': 4069571, 'author_profile': 'https://Stackoverflow.com/users/4069571', 'pm_score': 0, 'selected': False, 'text': '<p>By now, it has been 11 years since this question was asked and today, we can solve this problem using only <strong>standard C++11</strong>, i.e. cross-platform and without the need for a debugger or cumbersome logging.\nYou can trace the call stack that led to an exception</p>\n\n<h2>Use <a href="http://en.cppreference.com/w/cpp/error/nested_exception" rel="nofollow noreferrer"><code>std::nested_exception</code></a> and <a href="http://en.cppreference.com/w/cpp/error/throw_with_nested" rel="nofollow noreferrer"><code>std::throw_with_nested</code></a></h2>\n\n<p>This won\'t give you a stack unwind, but in my opinion the next best thing.\nIt is described on StackOverflow <a href="https://stackoverflow.com/a/37227893/4069571">here</a> and <a href="https://stackoverflow.com/a/348862/4069571">here</a>, how you can <strong>get a backtrace on your exceptions</strong> inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.</p>\n\n<p>It will, however, require that you insert try/catch statements at the functions you wish to trace (i.e. functions without this will not appear in your trace).\nYou could automate this with macros, reducing the amount of code you have to write/change.</p>\n\n<p>Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!\nYou may also take a look at my <a href="https://github.com/GPMueller/mwe-cpp-exception" rel="nofollow noreferrer">MWE on GitHub</a>, where a backtrace would look something like this:</p>\n\n<pre><code>Library API: Exception caught in function \'api_function\'\nBacktrace:\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/36077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3153/']