C++ unhandled exceptions - c++

Does C++ offer a way to 'show' something visual if an unhandled exception occurs?
What I want to do is to make something like assert(unhandled exception.msg()) if it actually happens (like in the following sample):
#include <stdexcept>
void foo() {
throw std::runtime_error("Message!");
}
int main() {
foo();
}
I expect this kind of code not to terminate immediately (because exception was unhandled), rather show custom assertion message (Message! actually).
Is that possible?

There's no way specified by the standard to actually display the message of the uncaught exception. However, on many platforms, it is possible anyway. On Windows, you can use SetUnhandledExceptionFilter and pull out the C++ exception information. With g++ (appropriate versions of anyway), the terminate handler can access the uncaught exception with code like:
void terminate_handler()
{
try { throw; }
catch(const std::exception& e) { log(e.what()); }
catch(...) {}
}
and indeed g++'s default terminate handler does something similar to this. You can set the terminate handler with set_terminate.
IN short, no there's no generic C++ way, but there are ways depending on your platform.

Microsoft Visual C++ allows you to hook unhandled C++ exceptions like this. This is standard STL behaviour.
You set a handler via a call to set_terminate. It's recommended that your handler do not very much work, and then terminate the program, but I don't see why you could not signal something via an assert - though you don't have access to the exception that caused the problem.

I think you would benefit from a catch-all statement as follows:
int main() {
try {
foo();
catch (...) {
// Do something with the unhandled exception.
}
}

If you are using Windows, a good library for handling unhandled exceptions and crashes is CrashRpt. If you want to do it manually you can also use the following I wrote in this answer.

If I'm reading your question correctly, you're asking if you can overload throw (changing its default behavior) so it does something user-defined. No, you can't.
Edit: since you're insistent :), here's a bad idea™:
#include <iostream>
#include <stdlib.h>
#include <windows.h>
void monkey() {
throw std::exception("poop!");
}
LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *lpTopLevelExceptionFilter) {
std::cout << "poop was thrown!" << std::endl;
return EXCEPTION_EXECUTE_HANDLER;
}
int main() {
SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter);
monkey();
return 1;
}
Again, this is a very bad idea, and it's obviously platform-dependent, but it works.

Yes, its possible. Here you go:
#include <iostream>
#include <exception>
void foo()
{
throw std::exception("Message!");
}
int main()
{
try
{
foo();
}
catch (std::exception& e)
{
std::cout << "Got exception: " << e.what() << std::endl;
}
return 0;
}

The c++ standard is the terminate handler - as other have said
If you are after better traceablility for throws then this is what we do
We have a macro Throw that logs the file name and line number and message and then throws. It takes a printf style varargs message.
Throw(proj::FooException, "Fingle %s unable to process bar %d", fingle.c_str(), barNo);
I get a nice log message
Throw FooException from nargle.cpp:42 Fingle barf is unable to process bar 99

If you're really interested in what happened to cause your program to fail, you might benefit from examining the process image in a post-mortem debugger. The precise technique varies a bit from OS to OS, but the basic train is to first enable core dumping, and compile your program with debug symbols on. Once the program crashes, the operating system will copy its memory to disk, and you can then examine the state of the program at the time it crashed.

Related

Get meaningful information from SEH exception via catch(...)?

Good Morning!
Edit: This is not a duplicate as it specifically pertains to SEH, not code-level thrown exceptions.
I'm using SEH to catch hardware errors thrown by some unreliable libraries. I'd like to get more information from the catchall exception. The following code simulates what I'm doing. As you can see, I'm using boost's current_exception_diagnostic_information, but it just spits out "No diagnostic information available." - not terribly helpful.
Is it possible to, at a minimum, get the termination code that would have been returned had the exception not have been caught? (In this case 0xC0000005, Access Violation)
#include "stdafx.h"
#include <future>
#include <iostream>
#include <boost/exception/diagnostic_information.hpp>
int slowTask()
{
//simulates a dodgy bit of code
int* a = new int[5]();
a[9000009] = 3;
std::cout << a[9000009];
return 0;
}
int main()
{
{
try
{
std::future<int> result(std::async(slowTask));
std::cout<< result.get();
}
catch(...)
{
std::cout << "Something has gone dreadfully wrong:"
<< boost::current_exception_diagnostic_information()
<< ":That's all I know."
<< std::endl;
}
}
return 0;
}
Using catch (...) you get no information at all, whether about C++ exceptions or SEH. So global handlers are not the solution.
However, you can get SEH information through a C++ exception handler (catch), as long as you also use set_se_translator(). The type of the catch should match the C++ exception built and thrown inside your translator.
The function that you write must be a native-compiled function (not compiled with /clr). It must take an unsigned integer and a pointer to a Win32 _EXCEPTION_POINTERS structure as arguments. The arguments are the return values of calls to the Win32 API GetExceptionCode and GetExceptionInformation functions, respectively.
Or you can use __try/__except, which are specific to SEH. They can be used inside C++ just fine, including in programs where C++ exceptions are used, as long as you don't have SEH __try and C++ try in the same function (to trap both types of exceptions in the same block, use a helper function).

When exactly has an exception been caught?

I get this terminating with uncaught exception even though I thought I had caught the exception. Here is some example code
#include <iostream>
#include <stdexcept>
void throwing(int x)
{
if(x) throw std::runtime_error("x non-null");
}
int main()
{
try {
throwing(1);
} catch(std::runtime_error const&ex) {
std::clog << "error: \"" << ex.what() << '\"' << std::endl;
std::terminate();
}
return 0;
}
which produces (after reporting error: "x non-null") the said message (using clang++ with std=c++11). So, when exactly has the exception been caught and hence deemed uncaught in the sense of terminate() not reporting it (again)? Or, equivalently (or not?): how can I catch an exception, report its what(), and terminate() without getting this blurb?
(I could refrain from reporting the what() and just terminate(), but I want to report the what() in my own way.)
Since noone provided an answer to this, and it seems like my comment was either not clear enough or overlooked, I'll post a full answer:
Or, equivalently (or not?): how can I catch an exception, report its what(), and terminate() without getting this blurb?
If you read carefully thru the reference, you'll notice std::terminate() by default calls abort(), which causes the program to terminate returning a platform-dependent unsuccessful termination error code to the host environment.
Now, answering the quoted question: either use exit(int status) (which is a better solution, since you handled the exception) instead of terminate, or change the terminate handler.

How to cause C++ throw to dump core if the exception would be handled by a particular catch block

Is there a way to cause a throw in C++ to dump core at the throw site if the thrown exception would be handled by a certain catch block? I would like something similar to what happens with g++ when an exception reaches the top level.
For example, I would like something like this:
try {
bar();
try {
foo();
} catch(...) {
# pragma dump_at_throw_site
}
} catch(...) {
std::cerr << "There was a problem" << std::endl;
}
This way, if any exception thrown from foo() or its callee's that reaches the call-site of foo() would cause a core dump at the throw site so one can see who threw the exception that made it to the to this level.
On the other hand, exceptions thrown by bar() would be handled normally.
Yes,it can in Windows. I don't know Linux, suppose it can also.
We can register a Exception Handler function to response the throw before the catch
Here is the code example:
#include <iostream>
#include "windows.h"
#define CALL_FIRST 1
LONG WINAPI
VectoredHandler(
struct _EXCEPTION_POINTERS *ExceptionInfo
)
{
UNREFERENCED_PARAMETER(ExceptionInfo);
std::cout <<"VectoredHandler"<<std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}
int main()
{
PVOID handler;
handler = AddVectoredExceptionHandler(CALL_FIRST,VectoredHandler);
try {
throw 1;
}catch(...)
{
std::cout <<"catch (...)"<< std::endl;
}
RemoveVectoredExceptionHandler(handler);
std::cout << "end of main"<<std::endl;
return 0;
}
The outputs of code are:
VectoredHandler
catch (...)
end of main
So,you can dump core int the function VectoredHandler.
The VectoredHandler is called after the debugger gets a first chance notification, but before the system begins unwinding the stack.
And if your purpose is just to debug the problem issue, then you can rely on the debugger feature to handle the first chance exception, don't need dump the application.
For your information, you may need know What is a First Chance Exception? in windows to understand how windows dispatch the exception.

How can some code be run each time an exception is thrown in a Visual C++ program?

If an exception is thrown in a C++ program control is either transferred to the exception handler or terminate() is called.
Even if the program emits some diagnostics from inside the handler (or from terminate() handler) that can be too late - the most value is in the call stack at the point where the exception is thrown, not in the handler.
On Windows a call stack can be obtained using [StackWalk64()]1 function. The key is how to call that function at the right moment.
Is there a way to make a Visual C++ program execute some user code each time an exception (or an exception for which no handler is set) is thrown?
If you want to do stuff when an SEH exception is thrown, such as when an access violation occurs, then you can simply catch the SEH exception (either with a __finally, or with a conversion to a C++ exception (see here)) and access the context within the exception which is the context at the time the exception was thrown. You can then generate either a callstack using StackWalker or a mini dump. IMHO it's better to produce a mini dump.
If you want to catch C++ exceptions at the point they're thrown and you don't have access to the source to the C++ exception classes then you need to get a bit craftier. I deal with this problem by running the target process under a custom debugger - use the Debug API (see here) which gets notifications of when an exception is thrown. At that point you can create a mini dump or call stack of the target process.
On Windows I'm using SetUnhandledExceptionFilter and MiniDumpWriteDump to produce a minidump.
__try, __except are very helpful.
Is there a way to make a Visual C++ program execute some user code each time an exception (or an exception for which no handler is set) is thrown?
Put that code into the constructor of your exception base class.
When the language doesn't support it, and you can't live without it, hack... :-/
#include <iostream>
#include <stdexcept>
namespace Throw_From
{
struct Line
{
Line& set(int x) { x_ = x; return *this; }
int x_;
template <typename T>
void operator=(const T& t) const
{
throw t;
}
};
Line line;
}
#define throw Throw_From::line.set(__LINE__) =
void fn2()
{
throw std::runtime_error("abc");
}
void fn1()
{
fn2();
}
int main()
{
try
{
fn1();
}
catch (const std::runtime_error& x)
{
std::cout << Throw_From::line.x_ << '\n';
}
}
This is a great article on how to catch all different types of exceptions in Visual C++.
It also provides you with a crash dump that comes useful for debugging.

Help with Try Catch

I'm using the GLUTesselator and every once in a while EndContour() fails so I did this:
try
{
PolygonTesselator.End_Contour();
}
catch (int e)
{
renderShape = false;
return;
}
Why would it still crash, it should perform the catch code right?
How could I fix this?
Thanks
Does PolygonTesselator.End_Contour(); crash or throws it an exception?
Note that a real "crash" (segfault, illegal instruction etc.) does not throw an exception in the sense of C++.
In these cases, the CPU triggers an interrupt - this is also sometimes called exception, but has nothing to do with an C++ exception.
In C++ you are running on a real CPU - and not in a virtual machine like in Java where every memory violation results in language execption like NullPointerException or ArrayOutOfBoundsException.
In C/C++ a CPU exception / interrupt / trap is handled by the operating system and forwarded to the process as "signal". You can trap the signal but usually this does not help for crashes (SIGSEG, SIGILL, SIGFPU, etcc.).
You're getting SEH exception, or Structured Exception Handling. These exceptions are thrown by Windows under an entirely different system since SEH predates C++, and can't be caught by a standard C++ catch block (MSVC does however provide SEH catching).
Alternatively, if you're on Unix, the kernel doesn't use C++ exceptions either. It uses signals. I don't pretend to understand signals, since I don't develop for Unix, but I'm very sure they're not C++ exceptions.
You've violated a hardware rule that you can't de-reference a NULL pointer. You'll get an OS-level error, by exception or signal. You can't catch these things in a C++ catch block just like that.
Edit: If you're using MSVC on Windows and have a recent compiler, you CAN enable /EHa, which allows you to catch Structured Exceptions as well as C++ exceptions. I wrote this code that functions as shown:
int main() {
std::string string = "lolcakes";
try {
Something s;
int i, j;
i = 0; j = 1;
std::string input;
std::cin >> input;
if (input == "Structured")
int x = j / i;
else
throw std::runtime_error("Amagad hai!");
}
catch(std::runtime_error& error) {
std::cout << "Caught a C++ exception!" << std::endl;
}
catch(...) {
std::cout << "Caught a structured exception!" << std::endl;
}
return main();
}
Structured Exceptions include Access Violations, your particular error.
Two things :
If you are under VC 6 or more recent, use __try{}__except(EXCEPTION_EXECUTE_HANDLER){} instead. It will catch the SE. try/catch only catches C++ exceptions
I've had a hard time with GLU, so I can tell you this : if you can set the normal, SET IT. But otherwise, it's true that it's quite solid.
Since all you want to do when the exception arrives is set 'renderShape' to false I'd recomment the following code:
try
{
PolygonTesselator.End_Contour();
}
catch (...) // takes any type of exception
{
renderShape = false;
return;
}
That said of course if you really can't fix the source to the exception itself!!
Why would it still crash, it should
perform the catch code right? How
could I fix this?
Most likely because you are not actually catching what is being thrown. Are you sure that PolygonTesselator.End_Contour(); throws an int?
If your program fails with the message error reading from location 0x000000000, then it is not failing because of an exception, but because of a segfault. You can use the segvcatch utility to convert segfaults into catchable exceptions. Check out their examples.
As mentioned, this is an SEH Exception.
If you are using Visual Studio, you can configure your project to catch SEH exceptions in your try/catch block.
Project Properties > C/C++ > Code
Generation > Enable C++ Exceptions >
Yes with SEH Exceptions