gdb catch throw and then ignore exceptions - c++

I have a crash in a multi threaded application and for whatever reason I can't manage to catch the exception before the stack is partially unwound.
So now I am trying to catch it by connected with gdb and using catch throw. However, I am getting lots of other unrelated and caught exceptions. How can I ignore those?
I tried ignore 1 1000000, but this doesn't ignore just the exception currently focused, but ignores all catch throw exceptions.
Any ideas how I can ignore that particular one only? e.g. maybe by file and line number?

Since version 7.9, gdb has included some convenience functions like $_caller_is and $_any_caller_is. These can be used as conditions on a breakpoint to make it stop only when a certain call stack is seen.
So, for example, if you know the spot at which the exception is thrown, you could do something like:
(gdb) catch throw if $_any_caller_is("functionname")
However, if you know the throwing function, it seems to me that it would be simpler to just set a breakpoint at that particular throw.
Another option in some situations is to filter the exception by type. This functionality is built into catch throw since version 7.7. This form accepts a regular expression matching the type name:
(gdb) catch throw NameOfType

Related

Is there a better way to see which function caused a exception other than using catch

I'm having problems with locating the address from which a error occurred, my whole code is running inside of a "try" statement and sadly whenever something is wrong I need to find the error using the old try and fail method by deleting parts of my code. Is there a better way to do it?
My current code:
try
{
do
{
if (somefunction)
if (somefunction2)
if (somefunction3)
if (somefunction4)
}
while (false);
}
catch (...)
{
// todo: somehow get the address where the error occurred
Logger::Log("Exception\n");
}
A simple solution to find out where an exception comes from is to use a unique message within each function. Catch the exception object and print the message. Or perhaps use even a different type of exception which will allow you to efficiently handle each case differently if that's what you want to do.
As for getting an "address", the trace of function calls that lead to the current point of execution is called a stacktrace (or backtrace). The stacktrace would contain information such as addresses. Theres no standard way to get a stacktrace yet, although it has been proposed for C++23.
However, once you've caught the exception, the stack will have been "unwound" such that you can't know where the exception came from. What you could do, is get the stack trace in the code that may be throwing (each of them since you don't know which one is the thrower) and store the trace in the exception. A central place to do that would be within the constructor of a custom exception type. This pattern is common in standard exception handling of modern languages.
Lastly, you don't necessarily need to make any changes to the program, if you instead run the program in a debugger and break on a throw, you can get all the information you can possibly get.

Why wouldn't you declare main() using a function-try-block?

There are a few SO posts about whether or not declaring main() using function-try-block syntax is valid syntax, and the general consensus seems to be that it's perfectly valid. This left me wondering... is there any reason (performance, style, thread synchronization, multithreading) why one wouldn't use this syntax for main() as a general rule to catch any unhandled exceptions anywhere more gracefully?
Obviously, ideally there won't be unhandled exceptions, but they happen and I think it'd be nice to provide something more informative than the OS-specific default handler. For example, in my case, I'd like to provide a support email address to the user so they can report the crash and have my program submit a log to my cloud-based crash log.
For example, in my case, I'd like to provide a support email address to the user
Well, how are you going to do that in a server with no user-facing interface?
Actually, how are you going to do that even in a process with user-facing components, if you have no way to tell in the catch block what state they're in?
And, for those processes where you can't show the user anything useful (or don't have any concept of a "user" in the first place), what would you do in your catch block that would be better than the default terminate?
As for
... more informative than the OS-specific default handler ...
many OS' default behaviour will be to save a complete snapshot of the process execution state, at the point the un-handled exception is thrown, to a file for debugging. As the developer, I can't think of many default behaviours that would be more informative.
Admittedly I'd prefer something more polished as the end user of a desktop app, but that's a pretty small subset of C++ programs.
You can easily convert
int main() try {
// The real code of main
}
catch (...)
{
}
to
int realMain()
{
// The real code of main
}
int main()
{
try
{
return realMain();
}
catch ( ... )
{
}
}
without losing functionality/behavior.
I am going to guess that whether you use the first version or the second version is a matter of coding practices of a team. From a compiler and run time standpoint, I don't see any semantic difference.
If you happened to have a variable that you want to access in your catch block, you would need the curly braces to provide visibility. But even that could be handled with nested try/catch...
why one wouldn't use this syntax for main() as a general rule to catch
any unhandled exceptions anywhere more gracefully?
compatibility with C.
Sometimes there is no way to handle unhandled exceptions more gracefully.
Obviously, ideally there won't be unhandled exceptions, but they
happen and I think it'd be nice to provide something more informative
than the OS-specific default handler. For example, in my case, I'd
like to provide a support email address to the user so they can report
the crash and have my program submit a log to my cloud-based crash
log.
If unexpected exception happens you can not be sure that it is possible to handle it correctly. What are you going to do if there is a network error exception in your example. And trying to send e-mail causes another exception? There can be other errors when you can not be sure that your data is not corrupted and you can not be sure that your program can run correctly after this error. So if you don't know what error happened it is better to allow your program to crash.
You can implement another "watcher" service that checks if process is running and if it has been crashed it can send e-mail to your users with the logs and core dumps.
If you catch the (otherwise) uncaught object, you won't be able to figure out how the execution reached the throw by inspecting the stack trace, because when exception handler is executed, the stack has already been unwound.
If you let the unexpected exception to be uncaught, you may be able to inspect the stack trace in the terminate handler - this is not guaranteed by the standard, but that's not a big deal since there is no standard way to inspect the stack trace either (in C++). You can either use platform specific API within the program, or an external debugger for the inspection.
So for example in your case, the advantage of not catching the exception would be that you can attach a stack trace to the log entry that you intend to submit.
Also, there are cases where an exception can not be handled by a catch block. For example, when you throw from a destructor that is being executed as a result of throwing an exception. So, to handle these "uncatchable" exceptions, you need a terminate handler anyway, so there is little advantage in duplicating the functionality in the case of uncaught exceptions.
As for the syntax that you use to catch the exception, there is no difference. The case where the function try block is different is a constructor, where it allows catching exceptions thrown by sub object constructors.

lldb - breaking before C++ exception thrown

In lldb I'd like to break before C++ throws the exception, on when the actual signal is generated. I'd like to do this for any type of exception.
The following command will break on the C++ throw catcher
break set -E c++
I'd like to break on the cause of the exception and ignore the C++ throw/catch as if the application was crashing. I'd also like to do this for applications without source.
Is there any lldb voodoo I can use here?
I'm not entirely sure what you are asking.
Exceptions throws in C++ do two things, create the exception object, and then directly call some runtime routine (__cxa_throw on most Unixen) to implement the unwinding. The latter is the point where the exception breakpoint stops. There isn't any more preliminary than this that you could hook onto.
You could try breaking when the exception object is allocated. On OS X & Linux this is __cxa_allocate_exception, but I don't know if that will always get called or if there are alternate ways to make the exception... I don't see how you would gain much from that, however, it's just a couple of instructions later that you'll see the call to the throw method.
But maybe if you describe the problem you are actually trying to solve, we can answer more helpfully...

Win32 Thread Exits Unexpectedly

I'm writing a C++ application. I realized that one of my worker threads may terminate unexpectedly. The (VS 2005) debug log says:
The thread 'Win32 Thread' (0x5d98) has
exited with code -858993460
(0xcccccccc).
I surrounded all the worker thread code with a try/catch block. So, if the reason was an exception, I would catch it. But I can't:
try{
...
Connection* conn = connectionPool->getConnection(); // unexpected exit occurs here
...
} catch(exception& e) {
...
}
I have ten threads running concurrently, and only one of them gets crashed after some time, while the others continue running (and getting new [OCCI] connections).
Is there an exception type that is not caught by "exception"? Or what do I not know about threads/exceptions?
Thanks.
Not all errors raise C++ exceptions that can be caught with the C++ try...catch mechanism. For example, division by zero will not raise a C++ exception, but will cause undefined behaviour which may well make your application exit.
However, your code may be throwing things that are not derived from std::exception , so you may want to rewrite:
try{
Connection* conn = connectionPool->getConnection(); // unexpected exit occurs here
}
catch(exception& e) {
// handle things derived from std::exception
}
catch ( ... ) {
// handle things that are not so derived
}
which will deal with things like throw "eeek!";
Also, but nothing to do with the problem, you should normally catch exceptins via a const reference.
Is there an exception type that is not caught by "exception"?
Yes, SEH exceptions. To catch them you need to either use __try/__except MSVC extension (see Structured Exception Handling), or write a global SEH/VEH handler (see SetUnhandledExceptionFilter and AddVectoredExceptionHandler).
The easiest way to find the problem would be to run your application under a debugger and enable breaking on Win32 Exceptions. Whenever a Win32 Exception is encountered, the application would break into the debugger and you can find out whats going wrong.
If you are not debugging and want to catch a win32 structured exception, you have to use _set_se_translator api to set a translator function. The registered function will be called whenever there is a Win32 exception and you get a chance to convert it to a C++ exception of your choice.
catch(exception& e) catches C++ exceptions derived from std::exception, and nothing else.
It doesn't catch C++ exceptions that are not derived from that class (If I do throw 42, it won't be caught for example), and it doesn't catch exceptions or errors at the system level.
Windows uses Structured Exception Handling (SEH) to signal errors, and those are not caught with a plain C++ catch statement. This might include errors like division by zero, as well as access violations or pretty much anything else that might go wrong at the OS or hardware level.
The docs have a nice explanation of how to catch SEH exceptions.
I found an important clue. When you close a handle with CloseHandle function, the thread exits with code 0xCCCCCCCC. With the help of this clue, I realized that in a very rare situation, I close my thread's handle even though the thread's working. Why does it exit exactly while getting connection? That also has an explanation, but it's related to the structure of the code, which may be difficult to explain here.
Thank you all, who brainstormed with me on the exceptions issue :$.

How to debug a program that is terminating in an unhandled exception?

I am programming in C++ on Linux platform.
My program terminates with this (unhandled???) exception:
"terminate called after throwing an instance of 'long'"
Aborted
The code that is throwing the exception is inside try-catch block, then why should this happen??
The exception is thrown while returning from a function.
I am used to C programming and have very little experience in C++ (which is the main problem). I don't know how to debug this issue. I don't expect a solution but a direction/pointer for debugging this problem.
Thanks in advance.
You can run your application under gdb (having built it with debug info using -g) and get it to break when an exception is thrown using the command:
(gdb) catch throw
This will take you to the origin of the exception. Some more info is available in this question:
Run an application in GDB until an exception occurs
Note that it is somewhat unusual to throw an ordinal type (such as a long). It may be in some temporary code, so grepping around might find it quickly enough.
It there anywhere on the call-stack with a exception specification or here? If there is then you might have this problem - you probably want to remove all of them.
If you are using gcc, then you can add this code first thing in main():
#ifdef __GNUC__
std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
#endif // ifdef __GNUC__
(More details at http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt02ch06s02.html)
Which will give you a better traceback from such exceptions.
you are probably catching the wrong exception type
use
catch(long)
or
catch(...)
Normally, I would recommend to set a breakpoint in the constructor of the thrown type -- but in this case ... I must admit to never have experienced that somebody has thrown a long like
throw 42;
That seems to me strange. Some debuggers might be able to catch an exception when it is thrown.
Is the called function yours?
Use set_terminate to break GDB
Example for set_terminate() is here
When it trigged - use bt command in GDB to see backtrace