2

I'm writing a function that detaches the data from a container and returns the number of elements detached:

int detach(foo f)
{
    try {
        /*some code*/
        return m_ids.size();
    } finally {
        m_ids.clear();
    }
}

foo is an object that receives the data in m_ids, which is a java.util.List.

My concern: is this code safe? Will it return the size of m_ids before it's cleared?

3 Answers3

9

The code is safe. The return value is established (and stored somewhere) before the finally block is reached. Once the finally block has ran, the stored return value is sent to the function caller.

Note thought that if you had written, in poor coding style, return m_ids.size(); as the last statement in the finally block then 0 would have been returned to the caller: a return value in a finally block overrides any other return value.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Check the generated bytecode:

int detach(java.util.List);
    Code:
       0: aload_1
       1: invokeinterface #4,  1  // InterfaceMethod java/util/List.size:()I
       6: istore_2
       7: aload_1
       8: invokeinterface #5,  1  // InterfaceMethod java/util/List.clear:()V
      13: iload_2
      14: ireturn
      15: astore_3
      16: aload_1
      17: invokeinterface #5,  1  // InterfaceMethod java/util/List.clear:()V
      22: aload_3
      23: athrow

istore_2 is the operation that stores the result of size into a local variable, which is then loaded (iload_2) and get returned.

Maroun
  • 94,125
  • 30
  • 188
  • 241
-5

Your finally block will never execute if there no exception thrown.