eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll explore the finally keyword in Java. We’ll see how to use it alongside try/catch blocks in error handling. Though finally is intended to guarantee the execution of code, we’ll discuss exceptional situations in which the JVM does not execute it.

We’ll also discuss some common pitfalls where a finally block can have an unexpected outcome.

2. What Is finally?

finally defines a block of code we use along with the try keyword. It defines code that’s always run after the try and any catch block, before the method is completed.

The finally block executes regardless of whether an exception is thrown or caught.

2.1. A Quick Example

Let’s look at finally in a try-catch-finally block:

try {
    System.out.println("The count is " + Integer.parseInt(count));
} catch (NumberFormatException e) {
    System.out.println("No count");
} finally {
    System.out.println("In finally");
}

In this example, regardless of the value of the parameter count, the JVM executes the finally block and prints “In finally”.

2.2. Using finally Without a catch Block

Also, we can use a finally block with a try block regardless of whether a catch block is present:

try {
    System.out.println("Inside try");
} finally {
    System.out.println("Inside finally");
}

And we’ll get the output:

Inside try
Inside finally

2.3. Why finally Is Useful

We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception.

Note: try-with-resources can also be used to close resources instead of a finally block.

3. When finally Is Executed

Let’s have a look at all the permutations of when the JVM executes finally blocks, so we can understand it better.

3.1. No Exception Is Thrown

When the try block completes, the finally block is executed, even if there was no exception:

try {
    System.out.println("Inside try");
} finally {
    System.out.println("Inside finally");
}

In this example, we aren’t throwing an exception from the try block. Thus, the JVM executes all code in both the try and finally blocks.

This outputs:

Inside try
Inside finally

3.2. Exception Is Thrown and Not Handled

If there’s an exception and it is not caught, the finally block is still executed:

try {
    System.out.println("Inside try");
    throw new Exception();
} finally {
    System.out.println("Inside finally");
}

The JVM executes the finally block even in the case of an unhandled exception.

And the output would be:

Inside try
Inside finally
Exception in thread "main" java.lang.Exception

3.3. Exception Is Thrown and Handled

If there’s an exception and it is caught by the catch block, the finally block is still executed:

try {
    System.out.println("Inside try");
    throw new Exception();
} catch (Exception e) {
    System.out.println("Inside catch");
} finally {
    System.out.println("Inside finally");
}

In this case, the catch block handles the thrown exception, and then the JVM executes the finally block and produces the output:

Inside try
Inside catch
Inside finally

3.4. Method Returns from try Block

Even returning from the method will not prevent finally blocks from running:

try {
    System.out.println("Inside try");
    return "from try";
} finally {
    System.out.println("Inside finally");
}

Here, even though the method has a return statement, the JVM executes the finally block before handing the control over to the calling method.

We’ll get the output:

Inside try
Inside finally

3.5. Method Returns from catch Block

When the catch block contains a return statement, the finally block is still called:

try {
    System.out.println("Inside try");
    throw new Exception();
} catch (Exception e) {
    System.out.println("Inside catch");
    return "from catch";
} finally {
    System.out.println("Inside finally");
}

When we throw an exception from the try block, the catch block handles the exception. Though there is a return statement in the catch block, the JVM executes the finally block before handing control over to the calling method, and it outputs:

Inside try
Inside catch
Inside finally

4. When finally Isn’t Executed

Although we always expect the JVM to execute the statements inside a finally block, there are some situations where the JVM will not execute a finally block.

We might already expect that if the operating system stops our program, then the program would not get the chance to execute all of its code. There are also some actions we can take that will similarly prevent the execution of a pending finally block.

4.1. Invoking System.exit

In this case, we are terminating the JVM by calling System.exit and hence the JVM will not execute our finally block:

try {
    System.out.println("Inside try");
    System.exit(1);
} finally {
    System.out.println("Inside finally");
}

This outputs:

Inside try

4.2. Invoking halt

Similar to System.exit, a call to Runtime.halt also halts  the execution and the JVM does not execute any finally blocks:

try {
    System.out.println("Inside try");
    Runtime.getRuntime().halt(1);
} finally {
    System.out.println("Inside finally");
}

Thus, the output will be:

Inside try

4.3. Daemon Thread

If a Daemon thread enters the execution of a try/finally block and all other non-daemon threads exit before the daemon thread executes the finally block, the JVM doesn’t wait for the daemon thread to finish the execution of finally block:

Runnable runnable = () -> {
    try {
        System.out.println("Inside try");
    } finally {
        try {
            Thread.sleep(1000);
            System.out.println("Inside finally");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
Thread regular = new Thread(runnable);
Thread daemon = new Thread(runnable);
daemon.setDaemon(true);
regular.start();
Thread.sleep(300);
daemon.start();

In this example, the runnable prints “Inside try” as soon as it enters the method and waits for 1 second before printing “Inside finally”.

Here, we start the regular thread and the daemon thread with a small delay. When the regular thread executes the finally block, the daemon thread is still waiting within the try block. As the regular thread completes execution and exits, the JVM also exits and does not wait for the daemon thread to complete the finally block.

Here’s the output:

Inside try
Inside try
Inside finally

4.4. JVM Reaches an Infinite Loop

Here’s a try block which contains an infinite while loop:

try {
    System.out.println("Inside try");
    while (true) {
    }
} finally {
    System.out.println("Inside finally");
}

Though it’s not specific to finally, it’s worth mentioning that if the try or catch block contains an infinite loop, the JVM will never reach any block beyond that loop.

5. Common Pitfalls

There are some common pitfalls that we must avoid when we use the finally block.

Although it’s perfectly legal, it’s considered bad practice to have a return statement or throw an exception from a finally block, and we should avoid it at all costs.

5.1. Disregards Exception

A return statement in the finally block ignores an uncaught exception:

try {
    System.out.println("Inside try");
    throw new RuntimeException();
} finally {
    System.out.println("Inside finally");
    return "from finally";
}

In this case, the method ignores the RuntimeException thrown and returns the value “from finally”.

5.2. Ignores Other return Statements

A return statement in the finally block ignores any other return statement in the try or catch block. Only the return statement in the finally block executes:

try {
    System.out.println("Inside try");
    return "from try";
} finally {
    System.out.println("Inside finally");
    return "from finally";
}

In this example, the method always returns “from finally” and completely ignores the return statement in the try block. This could be a very difficult bug to spot, which is why we should avoid using return in finally blocks.

5.3. Changes What’s Thrown or Returned

Also, in the case of throwing an exception from a finally block, the method disregards the exception thrown or return statements in the try and catch blocks:

try {
    System.out.println("Inside try");
    return "from try";
} finally {
    throw new RuntimeException();
}

This method never returns a value and always throws a RuntimeException.

While we may not intentionally throw an exception from the finally block as in this example, we may still encounter this issue. It can occur when cleanup methods we use in a finally block throw an exception.

6. Conclusion

In this article, we discussed what finally blocks do in Java and how to use them. Then, we looked at different cases where the JVM executes them, and a few when it might not.

Lastly, we looked at some common pitfalls associated with using finally blocks.

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

eBook Jackson – NPI EA – 3 (cat = Jackson)