Finding out the source of an exception in C++ after it is caught?

I'm looking for an answer in MS VC++.

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.

Example in pseudo code:

FunctionB()
{
    ...
    throw e;
    ...
}

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

try
{
    Function A()
}
catch(e)
{
    (<--- breakpoint)
    ...
}

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

One solution to my problem is to determine and save the call stack in the exception constructor (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.

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

Are there better solutions to this problem in other languages?

Answers


If you are just interested in where the exception came from, you could just write a simple macro like

#define throwException(message) { std::ostringstream oss; oss << __FILE __ << " " << __LINE__ << " " << __FUNC__ << " " << message; throw std::exception(oss.str().c_str()); }

which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).

Then throw exceptions using

throwException("An unknown enum value has been passed!");

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)


Need Your Help

F# “real world” apps?

f#

I'm starting to learn f#, and I really like it: now I wonder if "out there" someone has written any "real world" app in this wonderful language.

Getting IScroll 5 to work with Fancybox 2

jquery html css fancybox-2 iscroll

I am working on a project where I am using ISroll 5 to show some html code (that needs to scroll), placed over parts of images. Another part of the project has a button that when clicked shows a s...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.