main() 会捕获线程抛出的异常吗?
我有一个相当大的应用程序,它动态加载共享对象并在共享对象中执行代码。作为预防措施,我在 main
中的几乎所有内容都放置了 try/catch。我为 3 件事创建了一个 catch:myException
(内部异常)、std::exception
和 ...
(捕获所有异常) )。
作为共享对象执行的一部分,会创建许多pthread
。当线程抛出异常时,main
不会捕获该异常。这是标准行为吗?我怎样才能捕获所有异常,无论它们是从哪个线程抛出的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不
是的,这是标准行为。
要捕获源自线程
X
的异常,您必须在线程X
中使用try
-catch
子句(例如,围绕线程函数中的所有内容,类似于您在main
中已经执行的操作)。有关相关问题,请参阅如何在线程之间传播异常?
No
Yes, this is standard behaviour.
To catch an exception originating in thread
X
, you have to have thetry
-catch
clause in threadX
(for example, around everything in the thread function, similarly to what you already do inmain
).For a related question, see How can I propagate exceptions between threads?
你的问题是要求一些概念上不可能的东西。
Try 块被定义为堆栈的动态构造。 try 块从其内容捕获通过调用动态到达的代码抛出的异常。
当你创建一个新线程时,你会创建一个全新的堆栈,它根本不是 try 块的动态上下文的一部分,即使对 pthread_create 的调用是在 try 内部。
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.
不,main 不会捕获其他线程抛出的异常。您需要使用非标准的、特定于平台的工具来解决未处理的异常,以便按照您所描述的方式聚合处理。
当我构建此类应用程序时,我确保每个活动对象都有自己的顶级异常处理块,以防止在一个线程失败时整个应用程序崩溃。我认为使用特定于平台的包罗万象会导致您的整体代码/解决方案变得草率。我不会使用这样的东西。
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.
考虑抛出异常会展开堆栈。每个线程都有自己的堆栈。您必须在每个线程函数中(即每个线程的入口点)放置一个 try/catch 块。
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).