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?
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...
You could do that in catch block in case if you intend to send error condition to designated email id. finally block is generally used for graceful-release of the resources mostly. I do not recommend sending email or performing any business rules within the finally block.
Ideally you should have your business logic in Try block and Finally block should contain any cleanup task or any thing that must happen irrespective of success or failure of try block . You also need to make sure that the code in finally block does not cause any exception otherwise as Steven mentioned, the original exception will be lost if any.
In my mind,
try {
doSomethingFancy();
catch(Exception ex) {
logError(ex);
}
sendMail();
Is the perfect pattern for this. Finally block should only be used to clean the mess the code in the try block could have left behind.