Java:处理子线程中的异常 [英] Java: Handling exceptions in child threads
问题描述
我更喜欢在调用堆栈中更接近异常处理逻辑,在main方法附近。我喜欢这种方法...但是,我创建了一个线程,其中一些方法调用run()可能会抛出异常。我真的很想看看是否有一种方法可以将这些异常返回到父线程?我可以想到的最好的是在实现 Runnable
的对象内部设置一个变量。该变量是一个包含错误消息的字符串,然后使用类加载器在父线程中正确重新创建相同的异常。
I prefer to have the exception handling logic further up in the call stack, near the main method. I like this approach... However, I created a thread where some of its method calls inside run() may throw exceptions. I would really like to see if there is a way that these exceptions can be thrown back up to the parent thread? The best I could think of is setting a variable inside the object that implements Runnable
. This variable is a string that contains the Error Message, which then uses a class loader to correctly re-create the same exception in the parent thread.
我想要知道,有没有什么混乱的方式来获得我想要的东西? (能够确保在子线程中抛出的任何异常都使用相同的异常处理逻辑来处理,就好像它在主线程/代码重用中运行一样)。
What I would like to know, is there a less messy way of getting what I want here? (to be able to make sure that any exception thrown in a child thread is handled with the same exception handling logic as though it was running in the main thread/code re-use).
推荐答案
在run()方法的外层抓住它,然后将Exception放在Runnable中的一个变量中,并让Runnable指示它已完成。
Catch it at the outer level of your run() method then place the Exception in a variable in your Runnable and have your Runnable indicate that it completed.
开始运行的代码必须检查Runnable才能看到异常对象被设置并重新抛出或处理它。
The code that started your runnable has to then examine the Runnable to see that the "Exception" object is set and either rethrow it or deal with it.
如果你重新抛出,你可能希望将它包装在一个新的例外中:
If you rethrow it, you may want to wrap it in a new exception:
throw new Exception(oldException);
这将给你两个堆栈跟踪。
This will give you both stack traces.
(谢谢泰勒L)
这篇关于Java:处理子线程中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!