Search code examples
c#-3.0try-catch-finally

Can I have business logic in Finally block?


Is it advisable to have business logic in a finally block? I have to send an email notification when a job is over (whether successful or not). Can I place the email logic in finally block?


Solution

  • The main danger I can think of is that the finally block has the ability to silently swallow exceptions and return values from the try block itself.

    For example,

    try {
        doSomethingFancy();
    } finally {
        sendEmail();
    }
    

    If doSomethingFancy throws an exception, you will attempt to send an email. If somehow sending an email fails, sendEmail could throw an exception. This exception will "override" the original thrown one, and you'll never see it. It'll just vanish.

    You could code around this defensively with more try / catch blocks, but just be aware...