I can't find a way (neither through SO nor debugging my code) to allow an exception thrown from a tread to be propagated to the main thread. I have already tried using Thread.setUncaughtExceptionHandler()
and using CompletableFuture
: .exceptionally()
, .handle()
,...
The point is that with these mechanisms (as I debug), the actual handling is performed on the worker thread, not main thread -and I cannot manage to get it to to the main thread.
The overall point is that I'm writing a test and that if the exception raises in the worker thread, it never gets to the main thread where the test is running, making the test to pass even when something went wrong.
I would need that exception would raise asynchronous; I cannot wait for the future to complete as I need to immediately return a Stream (a PipedStream) without blocking, from the main tread.
The only tip I get is a console error (and only when I use the traditional Thread
+ uncaughtExceptionHandler
approach, no log at all when I try with CompletableFuture
):
Exception: com.example.exception.MyException thrown from the UncaughtExceptionHandler in thread "Thread-5"
or this if I don't define the exception handler:
Exception in thread "Thread-5" com.example.MyException: Exception message
I provide some code:
try {
@SuppressWarnings("squid:S2095") final PipedOutputStream pos = new PipedOutputStream();
final PipedInputStream pis = new PipedInputStream(pos);
CompletableFuture.runAsync(pipeDecryptorRunnable(inputStream, pos));
return pis;
} catch (IOException e) {
throw new CryptographyException(e.getMessage(), e);
}
Inside pipeDecryptorRunnable
is a CipherStream that decrypts data. The exception is thrown there. But I cannot catch it in the main thread and becomes invisible. The pis
stream returning from this method is used to read and worker thread decrypts data on-the-fly as its being read prom pis
.
EDIT:
UncaughtExceptionHandler
as the answers in similar questions suggests does not work for my scenario as the handler code is invoked by worker thread, not the main one.