简体   繁体   中英

How to re-throw an exception to catch-block in another thread

I've code that looks like this:

public static void startService() {
            try{
            new Thread(new Runnable() {
                @Override
                public void run() {
                    throw new RuntimeException("Some exception");
                }
            }).start();
            }catch (Exception e){
                //Exception handling
            }
        }

How can I handle this exception in the catch() block in parrent thread? UPD : This threads have to work asynchronous

You have several options to handle exceptions thrown by threads. One is to have a general uncaught exceptions handler:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        //log the exception or handle it here if possible
    }
});

But it is difficult to link an exception caught that way with a specific thread.

Or you can use an ExecutorService instead of starting the thread manually:

ExecutorService executor = Executors.newCachedThreadPool();
Future<?> future = executor.submit(new Runnable() {
    @Override
    public void run() {
        throw new RuntimeException("Some exception");
    }
});

try {
   future.get();
} catch (ExecutionException e) {
    Throwable yourException = e.getCause(); //here you can access the exception
}

抛出异常只是在catch块中添加throw e

If you mean it is inside of Runnable's run() method then you will have to use another approach. Use Callable instead! Callable call() method allows you to return a value and throw an exception.

Please have a look here for an example on how to use Callable . Also, note that it is better to use a higher level api such as ExecutorService which manages the lifecycle of your threads and provides thread pooling. (included in the example)

you would have to use an Callable.

The thread.run method will never throw an exception since it is - well - executed in a different thread and in this was will not interfere with your calling thread.

if you execute a callable (by eg running it via an ExecutorService) you get a Future result which in turn will throw the given exception when calling the future.get() method.

Use throw statement in catch block.

public static void startService() {
        try{
        new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();
        }catch (Exception e){
            throw e;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM