0

I am using Runnable thread which is looks like this:

private void startCalculateThread() { new Thread(new Runnable() { @Override public void run() { try { // calculatingSomething(); } catch (Exception e) { throw new RuntimeException(); } } }).start(); } 

Then I am calling this startCalculateThread method in some other method calculate like this:

private void calculate(final String message){ startCalculateThread(); } 

I am throwing RuntimeException from new Thread in startCalculateThread method. I figured out I can use Callable but I don't want to do that. Can someone tell how to get thrown exception from thread into calling method calculate.

1
  • 4
    This would not make sense. The calling method calculate has long finished when the thread is still running and eventually throwing. Commented Feb 2, 2018 at 8:06

2 Answers 2

3

I agree with @Henry - you wanted separated program flow but not in case of exception. You should rethink what you want to achieve.

This is not exactly what you wanted (exception is not handled in calculate), but might be what you are looking for...

import java.lang.Thread.UncaughtExceptionHandler; public class ThreadTest implements UncaughtExceptionHandler { public static void main(String[] args) { Thread t = new Thread(new Runnable() { @Override public void run() { throw new RuntimeException(); } }); t.setUncaughtExceptionHandler(new ThreadTest()); // <= check this t.start(); System.out.println("finished"); } @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("exception"); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

Threads have their own execution flow.
So you cannot "directly" catch the exception from the calculate() method.
But you can do it "indirectly" by using the Thread.setUncaughtExceptionHandler() method for the thread which you want to capture the thrown exception. As the exception is thrown, the uncaughtException() event will transmit the information of the exception thrown and the thread that has throws it.

You could modify your actual code as :

private void calculate(final String message){ Thread t = new Thread(new Runnable() { @Override public void run() { try { // calculatingSomething(); } catch (Exception e) { throw new RuntimeException(); } } }); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { // handling the exception } }); t.start(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.