DatabaseMetadata: NPE hides exception in finally block

Description

There a is problem when an exception occurs in org.hibernate.tool.hbm2ddl.DatabaseMetadata#initSequences:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 Statement statement = null; ResultSet rs = null; try { statement = connection.createStatement(); rs = statement.executeQuery(sql); while ( rs.next() ) { sequences.add( rs.getString(1).toLowerCase().trim() ); } } finally { rs.close(); statement.close(); }

If rs = statement.executeQuery(sql) fails, then in finally block we try to invoke close() method on rs object, which is still null. According to JLS §14.20.2.:

If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

So the reason why statement.executeQuery(sql) failed is discarded and forgotten and NullPointerException is thrown. That makes it really hard to debug.

I found this bug when I in my Spring application I've tried to connect do DERBY database using H2Dialect:

1 2 3 4 5 6 7 8 9 10 11 12 <jdbc:embedded-database id="dataSource" type="DERBY"/> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="hello"/> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop> </props> </property> </bean>

Environment

None

Status

Assignee

Brett Meyer

Reporter

Mateusz Sulima

Fix versions

Labels

None

backPortable

None

Suitable for new contributors

Yes, likely

Requires Release Note

None

backportDecision

None

Components

Affects versions

4.3.6

Priority

Trivial