I have a pretty large application that dynamically loads shared objects and executes code in the shared object. As a precaution, I put a try/catch around almost everything in main. I created a catch for 3 things: myException (an in house exception), std::exception, and ... (catch all exceptions).
As part of the shared objects execution, many pthreads are created. When a thread throws an exception, it is not caught by main. Is this the standard behavior? How can I catch all exceptions, no matter what thread they are thrown from?
Will main() catch exceptions thrown from threads?
No
When a thread throws an exception, it is not caught by main. Is this the standard behavior?
Yes, this is standard behaviour.
To catch an exception originating in thread X, you have to have the try-catch clause in thread X (for example, around everything in the thread function, similarly to what you already do in main).
For a related question, see How can I propagate exceptions between threads?
Your question is asking for something that isn't conceptually possible.
Try blocks are defined as dynamic constructs of the stack. A try block catches exceptions thrown by code reached dynamically, by call, from its contents.
When you create a new thread, you create a brand-new stack, that is not at all part of the dynamic context of the try block, even if the call to pthread_create is inside the try.
No, main will not catch exceptions thrown from other threads. You would need to use a non-standard, platform specific facility that addresses unhandled exceptions in order to aggregate the handling the way you are describing.
When I build such applications, I make sure each active object has its own top-level exception handling block, precisely to prevent the entire application from exploding if one thread fails. Using a platform-specific catch all I think begs for your overall code / solution to be sloppy. I would not use such a thing.
Consider that throwing an exception unwinds the stack. Each thread has its own stack. You will have to place a try/catch block in each thread function (i.e. in the entry point of each thread).
Related
I was reading thinking in c++ (exceptional handling).
I didn't understand following line
C++ exceptions cannot be used to handle asynchronous events because the exception and its handler are on the same call stack.
I tried searching over web but couldn't able to under stand this line.(specially call stack part)
Can anyone help on it?
EDIT:
what does same call stack means?
Exceptions, when thrown, divert the current thread's execution path to the handling of that exception. There's no way to avoid this by, say, getting another thread to perform the exception handling. The stack is important here because the exception handling involves stack-unwinding which isn't conducive to asyncronouis event handling, or much else.
The problem is like so
try {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do some really long running operation here
longFunctionToCalculate42();
// oops, some critical error!
throw std::runtime_error( "Something went wrong!" );
});
} catch ( const std::exception& e ) {
// this won't do what you think it does
std::cerr << e.what() << std::endl;
}
The asynchronous block is executed separately from the call site, and the caller of that asynchronous function (the dispatched block) cannot catch the exception thrown from it.
You actually can handle async events using exceptions. Weather or not you should is another matter. I'll only address that briefly: you usually shouldn't because there are more purpose-direct mechanisms to handle such things. Like passing messages between threads or raising some kind of event.
As to how you can accomplish this, what you have to do is catch the exception in the throw-ing thread, record the information somewhere, and have the other thread pick that up. Note that this really boils down fundamentally to passing messages between threads, with the additional complexity of stack unwinding and the like.
C++11 provides current_exception(), returning a exception_ptr, which provides the means to save the information about the exception somewhere the responding thread can pick it up. It is still up to you to build the code that actually retrieves and processes this exception_ptr up from wherever you saved it, and that's beyond the scope of this answer.
Note when thinking about this that, unless you need actual exceptions, doing this gains you nothing over simply passing messages between threads, and costs you the stack unwinding and semantic implications of throwing and catching exceptions.
It means that asynchronous events do not follow the exception's model where "exception and its handler are on the same call stack". That is -
exceptions rely on the dynamic chain of function calls on the program
s runtime stack (they have dynamic scope ), whereas asynchronous
events must be handled by completely separate code that is not part of
the normal program flow (typically, interrupt service routines or
event loops)
Note "completely separate code", which means that you'd have to rely on some other mechanism to handle asynchronous events (if you really need so).
In wikipedia we read:
Resource Acquisition Is Initialization RAII is a programming idiom
used in several object-oriented languages like C++, D, Ada and Vala.
The technique was invented by Bjarne Stroustrup to deal with resource
allocation and deallocation in C++. In this language, the only code
that can be guaranteed to be executed after an exception is thrown are
the destructors of objects residing on the stack.
I don't want to be over pedantic, whatever, but I really am not sure how to interpret this. Is this a slip of the tongue or is this correct? Aren't catch handlers guaranteed to be executed at least?
I know about RAII and what it is, I am focused here on this only code that can be guaranteed to be executed (..) are destructors of objects residing on the stack.
Strictly speaking, the quote is already wrong. When an exception is thrown and there's no matching handler for it, terminate can be called without unwinding the stack and calling any destructors. So, the statement that says that "destructors are guaranteed to be executed when an exception is thrown" is wrong.
As for catch handlers themselves, of course, it is only possible to execute a catch handler if the matching catch handler actually exists.
On top of that, even if the handler exists, there are other reasons that can throw a spanner in the works and prematurely terminate the processing of the exception before it reaches the catch handler. For example, it happens when an "unexpected" exception is thrown. If your function exception specification prohibits some specific exception type and an exception of such "prohibited" type attempts to "fly out" of that function, unexpected will be called immediately, instead of transferring control to the handler.
As mentioned in the comments, another typical situation is when new exception is thrown during stack unwinding triggered by a previous exception. This will result in terminate being called.
The only reason why I would say that Wikipedia is correct there is because if the exception causes the entire application to crash and stop execution, then it wouldn't make it down to the "catch" handler. For the most part you can guarantee that the catch clause will be found and executed.
Source: http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx
The C++ standard provides the std::set_terminate function which lets you specify what function std::terminate should actually call. std::terminate should only get called in dire circumstances, and sure enough the situations the standard describes for when it's called are dire (e.g. an uncaught exception). When std::terminate does get called the situation seems analagous to being out of memory -- there's not really much you can sensibly do.
I've read that it can be used to make sure resources are freed -- but for the majority of resources this should be handled automatically by the OS when the process exits (e.g. file handles). Theoretically I can see a case for if say, you needed to send a server a specific message when exiting due to a crash. But the majority of the time the OS handling should be sufficient.
When is using a terminate handler the Right Thing(TM)?
Update: People interested in what can be done with custom terminate handlers might find this non-portable trick useful.
This is just optimistic:
but for the majority of resources this should be handled automatically by the OS when the process exits
About the only resources that the OS handles automatically are "File Handles" and "Memory" (And this may vary across OS's).
Practically all other resources (and if somebody has a list of resources that are automatically handled by OS's I
would love that) need to be manually released by the OS.
Your best bet is to avoid exit using terminate() and try a controlled shut down by forcing the stack to unwind correctly.
This will make sure that all destructors are called correctly and your resources are released (via destructors).
About the only thing I would do is log the problem. So that when it does happened I could go back and fix the code so that it does not happen again. I like my code to unwind the stack nicely for resource deallocation, but this is an opinion some people like abrupt halts when things go badly.
My list of when terminate is called:
In general it is called when the exception handling mechanism cannot find a handler for a thrown exception. Some specific examples are:
An exception escapes main()
Note: It is implementation defined whether the stack is unwound here.
Thus I always catch in main and then rethrow (if I do not explicitly handle).
That way I guarantee unwinding of the stack (across all platforms) and still get the benefits of the OS exception handling mechanism.
Two exceptions propagating simultaneously.
An exception escapes a desatructor while another exception is propagating.
The expression being thrown generates an exception
An exception before or after main.
If an exception escapes the constructor/destructor of a global object.
If an exception escapes the destructor of a function static variable.
(ie be careful with constructors/destructors of nonlocal static object)
An exception escapes a function registered with atexit().
A rethrow when no exception is currently propagating.
An unlisted exception escapes a method/function that has exception specifier list.
via unexpected.
Similar to a statement made in Martin York's answer, about the only thing I do in a custom terminate handler is log the problem so I can identify and correct the offending code. This is the only instance I find that using a custom terminate handler is the Right Thing.
Since it is implementation-defined whether or not the stack is unwound before std::terminate() is called, I sometimes add code to generate a backtrace in order to locate an uncaught exception1.
1) This seems to work for me when using GCC on Linux platforms.
I think the right question would be how to avoid the calls to terminate handler, rather than when to use it.
I am not getting why if there is an active exception then if an exception is raised again, it leads to termination of program. Could someone explain?
What is it suppose to do? It can't "double catch" or anything, nor does it make sense to simply ignore one. The standard specifies that if, during stack unwinding, another exception escapes, then terminate shall be called.
There is more discussion in the C++ FAQ. One "solution" is to wrap your destructor code in a try/catch block, and simply don't let exceptions escape.
Another is to come up with some sort of custom exception chaining scheme. You'd do the above, but instead of ignoring an exception, you would append it to the currently thrown exception, and at the catch site handle both by hand.
The best solution, I think, it to try to remove the exceptional code from your destructor.
The reason is simple... if an exception is thrown during exception propagation, then which exception should be propagated? The original exception or the new exception? If the new exception is propagated and then handled, how will the program know that the other exception occurred? Or will the original exception be ignored? This and many other complications lead to the simple rule that only one exception may be propagated at a time, and multiple failures will result in the application being terminated.
Quoth the standard (15.2.3):
The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called ``stack unwinding.'' [Note: If a destructor called during stack unwinding exits with an exception, terminate is called (except.terminate). So destructors should generally catch exceptions and not let them propagate out of the destructor.
--- end note]
Basically C++ (as most other popular programming languages) has no good support for handling multiple errors using exceptions. Exceptions, as a mechanism, is simply deficient in that respect.
The FAQ has some suggestion on How to handle a destructor that fails?
Stroustroup has this to say on the matter (TCPL 14.7):
The reason for terminate() is that exception handling must occasionally be abandoned for less subtle error-handling techniques. For example, terminate() could be used to abort a process or maybe to re-initialize a system. The intent is for terminate() to be a drastic measure to applied when the error-recovery strategy implemented by the exception-handling mechanism has failed and it is time to go to another level of a fault tolerance strategy.
See also previous related discussion on SO: basically any question about exceptions and destructors.
This post has an explanation of the problem:
http://web.tiscali.it/fanelia/cpp-faq-en/exceptions.html#faq-17.3
When you throw an exception, it keeps unwinding the stack until it reaches an appropriate catch block. As part of the stack unwinding process, destructors are called for every object in each frame's scope.
Now, when a destructor throws an exception in this case, there's a dilemma -- which catch block is the program supposed to stop at? The original exception, or the new exception? Either way, there's an unprocessed exception involved.
Program's aren't good at making decisions like this, so the standard says it won't even try to resolve the issue and just gives up.
Check out the FAQ-Lite entry explaining this exact situation for further details.
Item 8 of Effective C++ says that you shouldn't ever allow an exception to leave a destructor.
I have a object of CCriticalSection in my class to synchronize the exceptions to a method. I use it with CSingleLock object like this:
void f()
{
try
{
CSingleLock lock(&m_synchronizer, TRUE);
.....
.....
}
catch(SomeException )
{
}
catch(...)
{
}
}
The critical section object is properly unlocked if any of the statement throws a C++ exception, however if I get any other type of exception (something like a access violation) is there any way I can unlock my critical section? I don't think RAII will help here as the stack unwinding doesn't happen. Is there any thing I can do to prevent the critical section being in locked state after exiting the function f?
EDIT Update
The destructor of CSingleLock will indeed unlock the underlying critical section. Access violations and the like are called SEH exceptions. As to whether or not the destructor will run in the face of an SEH exception is very environment specific. There are tricks you can do to make this type of scenario work.
For instance, one option is to translate all SEH exceptions into a corresponding C++ exception. I blogged recently on the technique to accomplish this. Once they're all C++ exceptions then the destructor being called is guaranteed.
http://blogs.msdn.com/jaredpar/archive/2008/01/11/mixing-seh-and-c-exceptions.aspx
But another question is why bother doing this? Once you're faced with at access violation the only thing your program can reliably do is crash.
Assuming you're using MSVC try compiling with the /EHa command line option which maps Windows' structured exceptions to C++ exceptions (the C++ docs sometimes call them 'asynchronous' exceptions).
You should read up on the implications of this - I don't use the option myself, and I'm not sure what the drawbacks might be.
You could also try using the __try, __except, __finally keywords to handle SEH yourself.
RAII does help here. The most important thing to not here is "going out of scope" is not necessarily just stack unwinding. When the try block is exited, either normally or through an exception, the destructor will be called. Anytime your variable goes out of scope its destructor is invoked.
Edit
Hmm it appears the question has been edited to focus on SEH (non C++ exceptions). In this case the destructor code might not be fired. However, as others have pointed out, most of the non-C++ exceptions are equivalent to application crashes. It may not be reasonable to react to these exceptions in any sane way other than to crash. In this case your app is exited and your critical section will be destroyed anyway.
See #JaredPar's answer for a good solution for translating C SEH exceptions to C++ exceptions for Windows.
If you really need your application to survive when a particular area of code performs an access violation, you should consider having that code in a separate process.
If code is trying to read or write to places it's not allowed, what's to stop it writing into other parts of your application's memory, causing all sorts of nasty problems?
AFAIK, you NEVER should use CCriticalSection nor any MFC synchronization object.