I am a java developer trying my hands on C-C++ code.
Basically I have some build script that uses Visual Studio components to build the application libraries - dlls. We do not use Visual Studio IDE to debug.
But whenever we face some crash in our application, we have to enter the debug statements line by line and need to check the exact line of code in which it is crashing.
Is there any API in C/C++ which would write the stack trace into a file during the crash of our program?
Some kind of event listener that would be called during a program exit and that could print the stack trace and error information into a log file.
I have seen many questions related to this but I am not able to get how to handle this in code rather than debugging tools. I feel Java is very much advanced with respect to error handling.
Thanks in advance!
The Standard does not give you any facilites for this. That said, you can use OS-specific APIs to get what you want. On windows, the easiest is probably to use StackWalker. You do need to take care of SEH oddities yourself. I suggest this article for more information.
On POSIX platforms, you can use the backtrace function from glibc.
In general, both require your program to be compiled with debug information. It is also possible to create crash dumps without symbol names (see Minidumps on Windows), but you will need to decode them (which Visual Studio does for you for example, but you mentioned in your post that you don't use it).
Also, keep in mind that writing crash dumps from a crashing process is very error-prone (since you really have no idea what state your application is at that time). You might get more reliable results if you write the crash dumps from another process. Earlier I've put together a simple example out-of-process crash handler that demonstrates how to implement that.
You can use std::set_terminate to define a function to be called when an exception leaves main() additionally you can install a signal handler for SIGSEGV to catch segmentation faults.
You can get a stack trace (on Linux) using libunwind ( http://www.nongnu.org/libunwind/ ) or use the backtrace() function from libc.
One thing I sometimes do in my own exception classes is to grab and store a stacktrace in the constructor that I can then obtain where I catch the exception and print the trace of where it was thrown from.
You could use <errno.h> in C to handle your error and log them into a log file. The standard flux for the errors is stderr.
One solution to get the error is to use the function perror included in <errno.h> that will display the exact error.
To use it, put it in an error catcher.
if (!fileIsOpen())
perror("File not opened");
I hope it helped.
We are using Google Test as our C++ unit testing framework. But I ran into a painful situation and don't know how to deal with.
Basically, when there is an uncaught exception in the code, I got the following error message printed in the console and get a FAILED. Obviously, the exception is captures by google test. However, I have no information at all where is the exception was throw.
unknown file: error: SEH exception with code 0xc000005 thrown in the test body.
What I can do is debug and step through the code and I will eventually figure out where the problem is. But this is not very efficient as the project is big.
I want the debugger to stop at the line of uncaught exception and give me a nice call stack. Is there any settings in google test that I don't know of? Any other work around or suggestions will be very much appreciated.
Edit: I am looking for something like the following under Windows
Finally according to the answers, I found this settings for visual studio and everything works as the way I want now :)
At work the approach I use is to run only the failing testcase using gdb like so:
gdb /path/to/test
catch throw
r --gtest_filter='Test.Testcase' --gmock_verbose=info
bt
With visual studio, I suspect you should be able to start your binary with arguments as above, and set a breakpoint to any throw, then take a look at the backtrace.
An SEH Exception is NOT a C++ exception.
It is a windows exception that is throw outside of the standard C++ framework for exception handing (there is a different syntax for catching them).
The best way to find the location is to run this inside DevStudio. Its been a while but I am sure DevStudio has an option to break when SEH exception is thrown. Just turn this on and your debugger will stop at the throw point and allow you to debug.
See: https://msdn.microsoft.com/en-us/library/d14azbfh.aspx
As noted by #MatthiasVegh you should pass the name of the test as well so you don't have to run through all the tests.
That is not possible since C++ doesn't keep stack trace in the exception object and even if gtest had some smart catching mechanism it would have no means to know where the exception came from. The best you can do is to store some information in the exception yourself and check it in the test case.
Is it possible to do the following? I'm very new to Windows programming so what I am asking for might range from impossible to nonsensical. If I understand correctly, errors such as division by zero or access violations are handled by the Windows structured exceptions mechanism. I would like to dump to a log file the maximal amount of information available including preferably a stack trace when a structured exception arises. I'm using MSVC10, windows 7.
Edit: A not unrelated question is whether this is a reasonable thing to do? Would the stack contain enough usable information to help in debugging ie, names of functions. Also, what is the best way do dump the stack having caught this exception?
Thanks
Yes, it's possible. Here you can find a sample: try-except Statement.
But it's better to consider dump creation for unexpected SEH exceptions, otherwise it could be difficult to find the cause.
Today, in my C++ multi-platform code, I have a try-catch around every function. In every catch block I add the current function's name to the exception and throw it again, so that in the upmost catch block (where I finally print the exception's details) I have the complete call stack, which helps me to trace the exception's cause.
Is it a good practice, or are there better ways to get the call stack for the exception?
What you are doing is not good practice. Here's why:
1. It's unnecessary.
If you compile your project in debug mode so that debugging information gets generated, you can easily get backtraces for exception handling in a debugger such as GDB.
2. It's cumbersome.
This is something you have to remember to add to each and every function. If you happen to miss a function, that could cause a great deal of confusion, especially if that were the function that caused the exception. And anyone looking at your code would have to realize what you are doing. Also, I bet you used something like __FUNC__ or __FUNCTION__ or __PRETTY_FUNCTION__, which sadly to say are all non-standard (there is no standard way in C++ to get the name of the function).
3. It's slow.
Exception propagation in C++ is already fairly slow, and adding this logic will only make the codepath slower. This is not an issue if you are using macros to catch and rethrow, where you can easily elide the catch and rethrow in release versions of your code. Otherwise, performance could be a problem.
Good practice
While it may not be good practice to catch and rethrow in each and every function to build up a stack trace, it is good practice to attach the file name, line number, and function name at which the exception was originally thrown. If you use boost::exception with BOOST_THROW_EXCEPTION, you will get this behavior for free. It's also good to attach explanatory information to your exception that will assist in debugging and handling the exception. That said, all of this should occur at the time the exception is constructed; once it is constructed, it should be allowed to propagate to its handler... you shouldn't repeatedly catch and rethrow more than stricly necessary. If you need to catch and rethrow in a particular function to attach some crucial information, that's fine, but catching all exceptions in every function and for the purposes of attaching already available information is just too much.
No, it is deeply horrible, and I don't see why you need a call stack in the exception itself - I find the exception reason, the line number and the filename of the code where the initial exception occurred quite sufficient.
Having said that, if you really must have a stack trace, the thing to do is to generate the call stack info ONCE at the exception throw site. There is no single portable way of doing this, but using something like http://stacktrace.sourceforge.net/ combined with and a similar library for VC++ should not be too difficult.
One solution which may be more graceful is to build a Tracer macro/class. So at the top of each function, you write something like:
TRACE()
and the macro looks something like:
Tracer t(__FUNCTION__);
and the class Tracer adds the function name to a global stack on construction, and removes itself upon destruction. Then that stack is always available to logging or debugging, maintenance is much simpler (one line), and it doesn't incur exception overhead.
Examples of implementations include things like http://www.drdobbs.com/184405270, http://www.codeproject.com/KB/cpp/cmtrace.aspx, and http://www.codeguru.com/cpp/v-s/debug/tracing/article.php/c4429. Also Linux functions like this http://www.linuxjournal.com/article/6391 can do it more natively, as described by this Stack Overflow question: How to generate a stacktrace when my gcc C++ app crashes. ACE's ACE_Stack_Trace may be worth looking at too.
Regardless, the exception-handling method is crude, inflexible, and computationally expensive. Class-construction/macro solutions are much faster and can be compiled out for release builds if desired.
The answer to all your problems is a good debugger, usually http://www.gnu.org/software/gdb/ on linux or Visual Studio on Windows. They can give you stack traces on demand at any point in the program.
Your current method is a real performance and maintenance headache. Debuggers are invented to accomplish your goal, but without the overhead.
There's a nice little project that gives a pretty stack trace:
https://github.com/bombela/backward-cpp
Look at this SO Question. This might be close to what you're looking for. It isn't cross-platform but the answer gives solutions for gcc and Visual Studio.
One more project for stack-trace support: ex_diag. There are no macros, cross-platform is present, no huge code needs, tool is fast, clear and easy in use.
Here you need only wrap objects, which are need to trace, and they will be traced if exception occurs.
Linking with the libcsdbg library (see https://stackoverflow.com/a/18959030/364818 for original answer) looks like the cleanest way of getting a stack trace without modifying your source code or 3rd party source code (ie STL).
This uses the compiler to instrument the actual stack collection, which is really want you want to do.
I haven't used it and it is GPL tainted, but it looks like the right idea.
While quite a few counter-arguments have been made in the answers here, I want to note that since this question was asked, with C++11, methods have been added which allow you to get nice backtraces in a cross-platform way and without the need for a debugger or cumbersome logging:
Use std::nested_exception and std::throw_with_nested
It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code by simply writing a proper exception handler which will rethrow nested exceptions.
It will, however, require that you insert try/catch statements at the functions you wish to trace.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!
You may also take a look at my MWE on GitHub or my "trace" library, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
An exception that isn't handled is left for the calling function to handle. That continues until the exception is handled. This happens with or without try/catch around a function call. In other words, if a function is called that isn't in a try block, an exception that happens in that function will automatically be passed up to call stack. So, all you need to do is put the top-most function in a try block and handle the exception "..." in the catch block. That exception will catch all exceptions. So, your top-most function will look something like
int main()
{
try
{
top_most_func()
}
catch(...)
{
// handle all exceptions here
}
}
If you want to have specific code blocks for certain exceptions, you can do that too. Just make sure those occur before the "..." exception catch block.
I've managed to get through my C++ game programming career so far virtually never touching exceptions but recently I've been working on a project with the Ogre engine and I'm trying to learn properly. I've found a lot of good questions and answers here on the general usage of C++ exceptions but I'd like to get some outside opinions from here on whether Ogre's usage is good and how best to work with them.
To start with, quoting from Ogre's documentation of it's own Exception class:
OGRE never uses return values to indicate errors. Instead, if an error occurs, an exception is thrown, and this is the object that encapsulates the detail of the problem. The application using OGRE should always ensure that the exceptions are caught, so all OGRE engine functions should occur within a try{} catch(Ogre::Exception& e) {} block.
Really? Every single Ogre function could throw an exception and be wrapped in a try/catch block? At present this is handled in our usage of it by a try/catch in main that will show a message box with the exception description before exiting. This can be a bit awkward for debugging though as you don't get a stack trace, just the function that threw the error - more important is the function from our code that called the Ogre function. If it was an assert in Ogre code then it would go straight to the code in the debugger and I'd be able to find out what's going on much easier - I don't know if I'm missing something that would allow me to debug exceptions already?
I'm starting to add a few more try/catch blocks in our code now, generally thinking about whether it matters if the Ogre function throws an exception. If it's something that will stop everything working then let the main try/catch handle it and exit the program. If it's not of great importance then catch it just after the function call and let the program continue. One recent example of this was building up a vector of the vertex/fragment program parameters for materials applied to an entity - if a material didn't have any parameters then it would throw an exception, which I caught and then ignored as it didn't need to add to my list of parameters. Does this seem like a reasonable way of dealing with things? Any specific advice for working with Ogre is much appreciated.
You don't need to wrap every last call to Ogre in try { ... } catch. You do it wherever you can meaningfully deal with the exception. This may be at the individual call site in some cases, or it could be in a high-level loop of some sort. If you can't deal with it meaningfully anywhere, don't catch it at all; let the debugger take over.
In particular, you shouldn't catch exceptions in main() for precisely the reason you cite (at least, not during development; you should in production).
I don't know anything about Ogre, I'm afraid, but the general rule with exception handling is that you catch the exception as far as possible from the throw site, but no further. However, this is only possible if the code that throws the exception uses RAII to look after allocated resources. If the code uses dynamic allocation to plain pointers, or other forms of manual resource management, then you need try-blocks at the call site. If this is the case, I'd say use of exceptions is a bad idea.
You seem to be unaware of how to debug exceptions.
Either
Bring up the VS Debug/Exceptions
dialog and tick the C++ Exceptions
box. This will give you an
opportunity (a dialog appears) to debug when an
exception is thrown.
or
If you've built Ogre source, set a
breakpoint in the Ogre::Exception
constructor and when it attempts to throw one you'll break with
a call stack where the next level up is the throw site.