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 exceptionThat 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:

1

2

3

public void undeclared() {

throw new IOException();

}

The Java compiler fails with the message:

1

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:

1

2

3

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.

#java #spring

When Does Java Throw UndeclaredThrowableException?
1.25 GEEK