Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

multithreading - Java: Handling exceptions in child threads

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an ExecutorService here to submit a callable and receive a Future. At the point you would at the very least want the Exception to be propagated to the invoking thread you would invoke future.get()

future.get() will propogate any exception thrown in the call method to the thread that is invoking future.get(). So if your main thread invokes future.get() then the main thread will see any exceptions thrown.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...