views:

61

answers:

4

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?

+1  A: 

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...

Steven Schlansker
I have implemented (a couple times) helper classes that would run a series of actions, and catch exceptions/continue when a certain action failed. Once all actions were executed, if any exceptions were thrown, they would be rolled up into a master exception, and I would throw that.
Merlyn Morgan-Graham
A: 

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.

this. __curious_geek
A: 

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.

Kapilg
A: 

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.

VdesmedT
@VdesmedT But then as Steven has pointed, what would happen if sendMail throws an exception? Won't it just crash my system?
Mayank
Of course, but then you can enclose it in a separate try catch block. Whenever two pieces of code deal with Exception in different manner, you certainly need to place them in separate try catch block.
VdesmedT