开发者

Will main() catch exceptions thrown from threads?

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 开发者_StackOverflowmatter 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜