Try in finally block

178 views Asked by At
try
{
    operation1();
    operation2();
    ...
}
finally
{
    try
    {
        finalizer_operation1();
        finalizer_operation2();

    }
    finally
    {
        very_critical_finalizer_operation_which_should_occurs_at_the_end();
    }
}

Is this ok? To have finalizer as another try/finally block (because finalizer_operationX() may throw and I must ensure that very_critical...() will happens at the end.

Quick googling for try in finally block brings nothing (will delete question if you give me a duplicate link), it should work, but I am unsure in design and possible problems with it.

2

There are 2 answers

3
duffymo On BEST ANSWER

I would not write the code this way. I don't like nesting try/catch/finally constructs. I prefer one per method.

My preference is to wrap each of those calls in its own method.

try
{
    operation1();
    operation2();
    ...
}
finally
{
    cleanup();
}

public void cleanup() {
    try
    {
        finalizer_operation1();
        finalizer_operation2();

    }
    finally
    {
        very_critical_finalizer_operation_which_should_occurs_at_the_end();
    }
}
5
Bathsheba On

Of course it is. A finally block will execute if control flow enters the corresponding try block.

The only exception is a call that shuts down the VM.