locked
Returning from finally block RRS feed

  • Question

  • Why is it not possible to return from the finally clause of the try..catch block? I tried writing a return statement in the finally block. The message I got while compiling was "Control cannot leave the body of a finally clause", but when I throw an exception from finally block, it compiles without any error. I guess throwing an exception and return both make the control leave the body of the finally block. Please suggest the reasons for the respective behaviours.

    Regards,

    Asim.

    Thursday, August 10, 2006 11:48 AM

Answers

  • If the finally block was executing as the result of an exception being thrown in the try block, it doesn't make sense to return because there is still an unhandled exception being thrown.  Therefore, you cannot return from within the finally block.  You can, however, throw new exceptions, because the possibility that an exception would be thrown in the finally block is unavoidable.  However, it should never be done intentionally, as it replaces the original exception and prevents the program/debugger from seeing it.
    Thursday, August 10, 2006 2:30 PM

All replies

  • Why would you want to return from within a finally block? It exists so you can execute some code regardless of how a try block was exited. Normally you'd want to avoid throwing new exceptions there as well since if an exception was thrown in the try block it will be hidden by the new one.
    Thursday, August 10, 2006 12:04 PM
  • If the finally block was executing as the result of an exception being thrown in the try block, it doesn't make sense to return because there is still an unhandled exception being thrown.  Therefore, you cannot return from within the finally block.  You can, however, throw new exceptions, because the possibility that an exception would be thrown in the finally block is unavoidable.  However, it should never be done intentionally, as it replaces the original exception and prevents the program/debugger from seeing it.
    Thursday, August 10, 2006 2:30 PM