Some part of my code is throwing java.util.concurrent.ExecutionException exception. How can I handle this? Can I use throws clause? I am a bit new to java.
It depends on how mission critical your Future
was for how to handle it. The truth is you shouldn't ever get one. You only ever get this exception if something was thrown by the code executed in your Future
that wasn't handled.
When you catch(ExecutionException e)
you should be able to use e.getCause()
to determine what happened in your Future
.
Ideally, your exception doesn't bubble up to the surface like this, but rather is handled directly in your Future
.
You should investigate and handle the cause of your ExecutionException.
One possibility, described in "Java Concurrency in Action" book, is to create launderThrowable
method that take care of unwrapping generic ExecutionExceptions
void launderThrowable ( final Throwable ex )
{
if ( ex instanceof ExecutionException )
{
Throwable cause = ex.getCause( );
if ( cause instanceof RuntimeException )
{
// Do not handle RuntimeExceptions
throw cause;
}
if ( cause instanceof MyException )
{
// Intelligent handling of MyException
}
...
}
...
}
If you're looking to handle the exception, things are pretty straightforward.
public void exceptionFix1() {
try {
//code that throws the exception
} catch (ExecutionException e) {
//what to do when it throws the exception
}
}
public void exceptionFix2() throws ExecutionException {
//code that throws the exception
}
Keep in mind that the second example will have to be enclosed in a try-catch
block somewhere up your execution hierarchy.
If you're looking to fix the exception, we'll have to see more of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With