I am working on a function which takes a CompletableFuture<Object>
and needs to handle its result (or its exception).
I am modifying it so that under a certain condition, I need to throw an exception.
However, the compiler tells me that I'm not handling this new exception (Unhandled exception ...
).
The function looks like this:
- In the line
//<-- THIS IS NOT OK
is what I'm just adding - In the line
//<-- THIS IS OK
is what was already there
Code:
public void myFunction(CompletableFuture<Object> resultSupplier, boolean someCondition) {
resultSupplier.handleAsync((result, throwable) -> {
if (throwable != null) {
//do something with the throwable
} else {
if (someCondition) {
throw new Throwable("some throwable"); //<-- THIS IS NOT OK ("Unhandled exception: java.lang.Throwable")
}
try {
//do something with the result which may raise an exception
} catch (Throwable ex) {
//do something in the catch
throw ex; //<-- THIS IS OK
} finally {
//do something to finalize
}
}
return null; //I don't actually need the future, just to execute the code above
});
}
I am having some troubles understanding this. Why the compiler is ok rethrowing the caught throwable inside the try block, but it's not ok with re-throwing the throwable that I've added?
I must say that I understand more the compile error (I'm inside a BiFunction<>
so I can't throw checked exceptions) rather than the compiler's happiness over the throw ex
inside the catch
block, but mostly I would just like to understand what's going on here and why there is a difference between the two.
P.s. you can copy-paste the code snippet into an IDE to easily reproduce the issue.