1. Overview
In this tutorial, we’re going to see what causes Java to throw an instance of the UndeclaredThrowableException exception.
First, we’ll start with a bit of theory. Then, we’ll try to better understand the nature of this exception with two real-world examples.
2. The UndeclaredThrowableException
Theoretically speaking, Java will throw an instance of UndeclaredThrowableException when we try to throw an undeclared checked exception. That is, we didn’t declare the checked exception in the throws clause but we throw that exception in the method body.
One might argue that this is impossible as the Java compiler prevents this with a compilation error. For instance, if we try to compile:
public void undeclared() {
throw new IOException();
}
The Java compiler fails with the message:
java: unreported exception java.io.IOException; must be caught or declared to be thrown
Even though throwing undeclared checked exceptions may not happen at compile-time, it’s still a possibility at runtime. For example, let’s consider a runtime proxy intercepting a method that doesn’t throw any exceptions:
public void save(Object data) {
// omitted
}
If the proxy itself throws a checked exception, from the caller’s perspective, the save method throws that checked exception. The caller probably doesn’t know anything about that proxy and will blame the save for this exception.
In such circumstances, Java will wrap the actual checked exception inside an UndeclaredThrowableException and throw the UndeclaredThrowableException instead. It’s worth mentioning that the UndeclaredThrowableException itself is an unchecked exception.
Now that we know enough about the theory, let’s see a few real-world examples.
3. Java Dynamic Proxy
As our first example, let’s create a runtime proxy for java.util.List interface and intercept its method calls. First, we should implement the InvocationHandler interface and put the extra logic there:
public class ExceptionalInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("size".equals(method.getName())) {
throw new SomeCheckedException("Always fails");
}
throw new RuntimeException();
}
}
public class SomeCheckedException extends Exception {
public SomeCheckedException(String message) {
super(message);
}
}
This proxy throws a checked exception if the proxied method is size. Otherwise, it’ll throw an unchecked exception.
Let’s see how Java handles both situations. First, we’ll call the List.size() method:
ClassLoader classLoader = getClass().getClassLoader();
InvocationHandler invocationHandler = new ExceptionalInvocationHandler();
List<String> proxy = (List<String>) Proxy.newProxyInstance(classLoader,
new Class[] { List.class }, invocationHandler);
assertThatThrownBy(proxy::size)
.isInstanceOf(UndeclaredThrowableException.class)
.hasCauseInstanceOf(SomeCheckedException.class);
As shown above, we create a proxy for the List interface and call the size method on it. The proxy, in turn, intercepts the call and throws a checked exception. Then, Java wraps this checked exception inside an instance of UndeclaredThrowableException. This is happening because we somehow throw a checked exception without declaring it in the method declaration.
If we call any other method on the List interface:
assertThatThrownBy(proxy::isEmpty).isInstanceOf(RuntimeException.class);
Since the proxy throws an unchecked exception, Java lets the exception to propagate as-is.
4. Spring Aspect
The same thing happens when we throw a checked exception in a Spring Aspect while the advised methods didn’t declare them. Let’s start with an annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ThrowUndeclared {}
Now we’re going to advise all methods annotated with this annotation:
@Aspect
@Component
public class UndeclaredAspect {
@Around("@annotation(undeclared)")
public Object advise(ProceedingJoinPoint pjp, ThrowUndeclared undeclared) throws Throwable {
throw new SomeCheckedException("AOP Checked Exception");
}
}
Basically, this advice will make all annotated methods to throw a checked exception, even if they didn’t declare such an exception. Now, let’s create a service:
@Service
public class UndeclaredService {
@ThrowUndeclared
public void doSomething() {}
}
If we call the annotated method, Java will throw an instance of UndeclaredThrowableException exception:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = UndeclaredApplication.class)
public class UndeclaredThrowableExceptionIntegrationTest {
@Autowired private UndeclaredService service;
@Test
public void givenAnAspect_whenCallingAdvisedMethod_thenShouldWrapTheException() {
assertThatThrownBy(service::doSomething)
.isInstanceOf(UndeclaredThrowableException.class)
.hasCauseInstanceOf(SomeCheckedException.class);
}
}
As shown above, Java encapsulates the actual exception as a cause and throws the UndeclaredThrowableException exception instead.
5. Conclusion
In this tutorial, we saw what causes Java to throw an instance of the UndeclaredThrowableException exception.
As usual, all the examples are available over on GitHub.