Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW