Will main () catch exceptions from threads?

I have a fairly large application that dynamically loads shared objects and executes code in a shared object. As a precaution, I put try / catch on almost everything in main . I created a trick for 3 things: myException (exception from home), std::exception and ...

As part of the execution of shared objects, many pthreads are created. When a thread throws an exception, it does not fall under main . Is this standard behavior? How can I catch all exceptions, regardless of which thread they are thrown from?

+23
source share
4 answers

Will main () catch exceptions thrown from threads?

No

When a thread throws an exception, it does not get to the main one. Is this standard behavior?

Yes, this is standard behavior.

To catch an exception that comes from thread X , you must have a try - catch clause in thread X (for example, around everything in a thread function, similar to what you already do in main ).

For a related question, see How do I throw exceptions between threads?

+25
source

In your question, the question arises of what is conceptually impossible.

Block attempts are defined as dynamic stack designs. The try block catches the exceptions thrown by the code, which dynamically, when called, get from its contents.

When you create a new thread, you create a completely new stack that is not at all part of the dynamic context of the try block, even if the pthread_create call is inside the try.

+13
source

No, main will not catch exceptions from other threads. You will need to use a non-standard, platform tool that accesses unhandled exceptions in order to aggregate the processing as you describe.

When I create such applications, I make sure that every active object has its own top-level exception handling block to prevent the entire application from cracking completely if one thread fails. Using platform-specific catches is all I think requires your general code / solution to be sloppy. I would not use such a thing.

+8
source

Consider throwing an exception to expand the stack. Each thread has its own stack. You will need to place a try / catch block in each stream function (i.e., at the entry point for each stream).

+6
source

Source: https://habr.com/ru/post/1275111/


All Articles