Java Return from Finally

try…catch…finally is the common idiom in Java for exception handling and cleanup. The thing that people may not know is that returning from within a finally block has the unintended consequence of stoping an exception from propagating up the call stack. It “overrides” the throwing of an exception so that the caller will never get to handle it.

public class Main {
public static void main(String[] args) throws Throwable {
System.out.println("No way to know that an exception was thrown");

public static void method() throws Throwable {
try {
System.out.println("In method about to throw an exception.");
throw new RuntimeException();
} catch (Throwable ex) {
System.out.println("Caught exception, maybe log it, and then rethrow it.");
throw ex;
} finally {
System.out.println("return in finally prevents an exception from being passed up the call stack.");
return; // remove the return to see the real behavior

I recently came across code like this. This is Real Bad. Returning from within finally prevents the propagation of regular exceptions, which is bad enough, but worse, prevents the propagation of runtime exceptions which are generally programmer errors. This one small mistake can hide programmer errors so that you’ll never see them and never know why things aren’t working as expected. One of the interesting things is that the Java compiler understands this as well. If you return from within a finally block where an exception would otherwise be thrown, the compiler does not force you to declare that exception in the method’s throws declaration.

Long story short. Don’t return from with finally. Ever.

MongoDB and Java: Find an item by Id

MongoDB is one of a number of new databases that have cropped up lately eschewing SQL. These NoSQL databases provide non-relational models that are suitable for solving different kinds of problems. This camp includes document oriented, tabular and key/value oriented models among others. These non-relational databases are supposed to excel at scalability through parallelization and replication but sometimes (although not always) at the expense of some of the transactional guarantees of SQL databases.

Why would you care about any of this? Document oriented databases allow for each document to store arbitrary pieces of data. This could allow for much easier customization of data storage such as when you want to store custom fields. Many of these databases also make horizontal scaling quite simple as well as providing high performance for write heavy applications.

With this in mind I figured I should look and see what’s there. So I started looking at MongoDB.

Start by creating an object to add to the database

With MongoDB, a collection is conceptually similar to a table in a SQL database. It holds a collection of related documents. A DBObject represents a document that you want to add to a collection. MongoDB automatically creates an id for each document that you add. That id is set in the DBObject after you pass it to the save method of the collection. In a real world application you might need that id to later access the document.

DBObject obj = new BasicDBObject();
obj.put("title", getTitle());
obj.put("body", getBody());

DBCollection coll = db.getCollection("note"));;

String idString = obj.get("_id").toString();

Retrieve an object previously added to a collection

To get a document from MongoDB you again use a DBObject. It does double duty in this case acting as a the parameters you want to use to identify a matching document. (There are ways you can do comparisons other than equality, of course, but I’ll leave that for a later post.) Using this as a “query by example” model we can set the _id property that we previously retrieved. The one catch is that the id is not just a string, it’s actually an instance of an ObjectId. Fortunately when we know that it’s quite easy to construct an instance with the string value.

String idString = "a456fd23ac56d";
DBCollection coll = db.getCollection(getCollectionName());
DBObject searchById = new BasicDBObject("_id", new ObjectId(idString));
DBObject found = coll.findOne(searchById);

A couple of easy examples, but it wasn’t obvious to me when I started how to get the id of a document that I just added to the database. More to come in the future.

For more on MongoDB check out these books:

Struts2 Map Form to Collection of Objects

The Struts2 documentation contains examples that are often basic at best which can make it challenging to figure out how to do things sometimes. I was working on creating a form that would allow me to select values from a list to connect 2 objects in a One-to-Many relationship. This is a common relationship for many things. In this example, I’ll use a User and Role class to demonstrate the concept.

For background, here’s a JPA mapped User and Role class.

import java.util.List;
import javax.persistence.*;

public class User {

private Long id;
// ... other member variables
private List roles;

@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;

public void setId(Long id) { = id;

@JoinTable(name = "UserRoles",
joinColumns = @JoinColumn(name = "user_Id"),
inverseJoinColumns = @JoinColumn(name = "role_Id"),
uniqueConstraints = @UniqueConstraint(columnNames = {"user_Id", "role_Id"})
public List getRoles() {
return roles;

public void setRoles(List roles) {
this.roles = roles;

// ... other properties

public class Role {

private Long id;

@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;

public void setId(Long id) { = id;

// ... other properties

A list of Roles exists in the database. When a User is created, they are assigned one or more Roles. The User and Roles are connected in the Database through a join table as defined in the mapping. At this point I created some DAO Repository classes to manage the persistence and an Action to handle the form values. (The details of JPA, setting up Persistence and Actions are beyond the scope of this post.)

The part that caused me the most grief ended up being the form. I wanted to add a checkbox list that contained all of the Roles. The example on the Struts site for checkboxlist, a control with 43 documented properties is:

Needless to say, there was some ‘figuring out’ to be done.

The form itself is pretty vanilla for the most part. The checkboxlist is the interesting part because it’s what allows us to map the User to the Roles. I knew that I was looking for something to put into the value property of the control that would tell it to pre-select the Role values that were already associated with the User.

I started out with something like:

That didn’t work. When you think about it, that makes sense because the keys in the list are ids and the values supplied are Role objects. So I needed to figure out how to get the Ids from the Roles. I could have done that in the Action class, but it seemed like there should be a better way. A way that would allow me to continue in more of a Domain fashion.

Doing some research into OGNL, I came upon the list projections section which was the key…

The OGNL projection syntax gives us user.roles.{id}. Basically that is a list comprehension that takes of list of Role objects and turns it into a list of Role Ids. That list of Ids becomes the list of values that will be preselected.

Knowing that I can now create a select box that will include the pre-selected values on an edit form:


StringBuilder and my Biggest Pet Peeve

What You Should Know About Strings

In both Java and .NET (and other languages) String objects are immutable. They don’t change. Period. If you “change” a String, it creates a new String. That includes String concatenation using a +

// One string created "foo"
String foo = "foo";
// foo exists, "bar" is created and the combination of foo and "bar" is a third string
String bar = foo + " bar";

Ok, if you don’t know this, fine. But if you don’t know this, why would you EVER use a StringBuilder?

Why Does StringBuilder Exist?

We know that Strings are immutable. If you need to do a bunch of string modification, concatenation, replacement – you will create a bunch of strings. Ok, great…why do I care? We care because we are told that creating a lot of Objects (and then later having to Garbage Collect them) is inefficient. To start with, I will guarantee right now that concatenating strings WILL NOT be the thing that prevents your application from performing. Guaranteed. Period.

Ok fine, it’s not going to be a problem. But you want to be a responsible coder and not do things that are intentionally inefficient if you can help it.

So you use a StringBuilder. StringBuilder is implemented internally as an array of characters. The code manages the allocation and copying of data to new arrays if the buffer gets filled. It sometimes over allocates the new buffer so that it has to perform allocations less often. You sacrifice a bit of memory overhead to avoid some Object creation and Garbage Collection later.

My Biggest Pet Peeve

Your use of StringBuilder is a premature optimization but probably a forgivable one.

So, WHY, OH WHY do you do this:

// One string created "foo"
StringBuilder sb = new StringBuilder();
sb.append("Foo: " + fooValue + " \n");
sb.append("Bar: " + barValue + "\n");

It makes me have violent thoughts. Please stop.

For some of the reasons why Strings are immutable, see this post on immutability and its positive qualities.