-2

Possible Duplicate:
In Java, does return trump finally?

I came across a java code snippet in a dao implementation .It returns a List as shown below.

After the 'return' statement is executed,the finally block tries to close the session.Will this work? or will the session remain open?

thanks

mark

import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
...
public List<Item> findItems(String name) {
    SessionFactory factory = HibernateUtil.getSessionFactory();
    Session session = factory.openSession();
    try{
        Criteria cri = session.createCriteria(Item.class);
        return (List<Item>) cri.add(Restrictions.eq("name", name)).list();
    } finally {
        session.close();
    }
}
Community
  • 1
  • 1
markjason72
  • 1,583
  • 8
  • 24
  • 46

4 Answers4

5

The only time a finally block will not be executed is if you terminate your program such as System.exit(0) or force quit etc. So the answer is: Yes, your session will be closed.

LuckyLuke
  • 45,605
  • 80
  • 262
  • 423
3

Read up on The finally Block, and yes, the finally block will be executed after the return.

Moonbeam
  • 2,253
  • 1
  • 14
  • 17
2

Yes, finally blocks will always execute (*).

The finally block will execute "after" the return in the sense that the return value will be computed and remembered before the finally block is executed.

(*) caveat: unless something causes the JVM to end operation alltogether.

Joachim Sauer
  • 291,719
  • 55
  • 540
  • 600
0

Yes, the finally block will be executed after the return statement but before the value is fully returned to the method.

Buhake Sindi
  • 85,564
  • 27
  • 164
  • 223