There are several possibilities to find out where the exception was thrown:
Using compiler macros
Using __FILE__
and __LINE__
macros at throw location (as already shown by other commenters), either by using them in std exceptions as text, or as separate arguments to a custom exception:
Either use
throw std::runtime_error(msg " at " `__FILE__` ":" `__LINE__`);
or throw
class my_custom_exception {
my_custom_exception(const char* msg, const char* file, unsigned int line)
...
Note that even when compiling for Unicode (in Visual Studio), FILE expands to a single-byte string.
This works in debug and release. Unfortunately, source file names with code throwing exceptions are placed in the output executable.
Stack Walking
Find out exception location by walking the call stack.
On Linux with gcc the functions backtrace() and backtrace_symbols() can get infos about the current call stack. See the gcc documentation how to use them. The code must be compiled with -g, so that debug symbols are placed in the executable.
On Windows, you can walk the stack using the dbghelp library and its function StackWalk64. See Jochen Kalmbach's article on CodeProject for details. This works in debug and release, and you need to ship .pdb files for all modules you want infos about.
You can even combine the two solutions by collecting call stack info when a custom exception is thrown. The call stack can be stored in the exception, just like in .NET or Java. Note that collecting call stack on Win32 is very slow (my latest test showed about 6 collected call stacks per second). If your code throws many exceptions, this approach slows down your program considerably.