Can I have business logic in Finally block? - c#-3.0

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

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.

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.

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.

Related

Can a matlab function called within a script cause the script to break?

I am running a script which calls a function, and if a certain condition is met, inside the function, I want the whole thing just to terminate (and by that I do not mean I want to close matlab using exit). Is that possible? I know I can use return or break to return to the script, however I want the script to stop as well if this condition is met.
The only function I know of that does this is error. This throws an exception, and, if no exception handlers with try and catch are installed in the calling script, will terminate and return to command prompt. Which is what you want, as far as I understand. It prints an error message though. This could be suppressed if you guard all code in the top-level script with a try catch handler. However this will have to be specific to the one error and it makes debugging ("stop-on-error") much more difficult.
The thing is that the only use case I see for this behavior (termination of whole program on certain event) is when a non recoverable error occurs, and in that case printing an error message is indeed appropriate.
In case the script is successful termination of the whole program is not really the right way. All functions should return to give the upper layers of the code to perform some clean-up action, like saving the output data or so.

How is try catch evaluated in matlab?

I wonder how a try-catch block is evaluated in matlab. In particular, is the try-catch block evaluated in runtime or "compile time"?
Also, is a try-catch block expensive?
If someone have a link to any documentation that would be much appreciated.
(Btw, I know that try-catch is not the best solution in most cases. Still I would like to know how it works, since I have used it in some code).
try and catch blocks allow you to override the default error behavior
for a set of program statements. If any statement in a try block
generates an error, program control goes immediately to the catch
block, which contains your error handling statements.
To learn more about try and catch in Matlab:Try and Catch
Try and catch block is always executed in run-time and is used to catch the errors that occur and has error-handling statements. So if your code generates some error and you want to handle it, use it. Using error-handling is good programming practice..

How to request a replay of an already received fix message

I have an application that could potentitally throw an error on receiving a ExecutionReport (35=8) message.
This error is thrown at the application level and not at the fix engine level.
The fix engine records the message as seen and therefore will not send a ResendRequest (35=2). However the application has not processed it and I would like to manually trigger a re-processing of the missed ExecutionReport.
Forcing a ResendRequest (35=2) does not work as it requires modifying the expected next sequence number.
I was wonderin if FIX supports replaying of messages but without requiring a sequence number reset?
When processing an execution report, you should not throw any exceptions and expect FIX library to handle it. You either process the report or you have a system failure (i.e. call abort()). Therefore, if your code that handles execution report throws an exception and you know how to handle it, then catch it in that very same function, eliminate the cause of the problem and try processing again. For example (pseudo-code):
// This function is called by FIX library. No exceptions must be thrown because
// FIX library has no idea what to do with them.
void on_exec_report(const fix::msg &msg)
{
for (;;) {
try {
// Handle the execution report however you want.
handle_exec_report(msg);
} catch(const try_again_exception &) {
// Oh, some resource was temporarily unavailable? Try again!
continue;
} catch(const std::exception &) {
// This should never happen, but it did. Call 911.
abort();
}
}
}
Of course, it is possible to make FIX library do a re-transmission request and pass you that message again if exception was thrown. However, it does not make any sense at all because what is the point of asking the sender (over the network, using TCP/IP) to re-send a message that you already have (up your stack :)) and just need to process. Even if it did, what's the guarantee it won't happen again? Re-transmission in this case is not only doesn't sound right logically, the other side (i.e. exchange) may call you up and ask to stop doing this crap because you put too much load on their server with unnecessary re-transmit (because IRL TCP/IP does not lose messages and FIX sequence sync process happens only when connecting, unless of course some non-reliable transport is used, which is theoretically possible but doesn't happen in practice).
When aborting, however, it is FIX library`s responsibility not to increment RX sequence unless it knows for sure that user has processed the message. So that next time application starts, it actually performs synchronization and receives missing messages. If QuickFIX is not doing it, then you need to either fix this, take care of this manually (i.e. go screw with the file where it stores RX/TX sequence numbers), or use some other library that handles this correctly.
This is the wrong thing to do.
A ResendRequest tells the other side that there was some transmission error. In your case, there wasn't, so you shouldn't do that. You're misusing the protocol to cover your app's mistakes. This is wrong. (Also, as Vlad Lazarenko points out in his answer, if they did resend it, what's to say you won't have the error again?)
If an error occurs in your message handler, then that's your problem, and you need to find it and fix it, or alternately you need to catch your own exception and handle it accordingly.
(Based on past questions, I bet you are storing ExecutionReports to a DB store or something, and you want to use Resends to compensate for DB storage exceptions. Bad idea. You need to come up with your own redundancy solution.)

Is `finally` block executed in case there is `return` inside a `try` or a `catch` block?

Using a try-catch-finally construction to retrieve a database record, it seems that I need to return a value inside a try block in case everything was fine (as in case of an exception the end of the function is not meant to be reached). But If I return inside try, is finally code going to be reached (to close the connection etc.)?
Yes,
The result of the try/catch expression will be the last line of either the try or catch block, but the finally block will always execute no matter what
Yes.
The point of a finally is to ensure that some cleanup code is executed no matter what path the code uses to leave the try block. It happens on ordinary return, when an exception is thrown and caught, and when an exception is thrown that isn't caught by this try block. The only thing that will prevent it running is if the program is unable to leave the try block at all; an infinite loop inside it, or the process being killed by some means that prevents this normal processing from happening, or something of that order. I'm pretty sure even if you exit the process from inside the try block that the finally block will be executed before the process actually dies.

Idea for doing almost same work in both catch & finally(C#3.0)

I have a requirement.
I am processing some files and after the processing are done I am archiving those files into an archive folder with timestamp appended.
The file archiving and putting time stamp portion I am doing in the Finally block. Now a new requirement has come where I need to mail if something wrong goes in the original files and then I need to archive the same. Now this piece of code I need to handle in the catch block.
But if I write the code entirely in the catch block, then it will fire only if there is an exception; otherwise not.
So basically I am writing the same pice of code in both the catch and finally block.
What is the standard and recommended approach you people think will be better in this case?
I am using C#3.0
Thanks.
A finally block is really for code that "always" has to run, even after an exception. This typically means cleanup type code. It's a "code smell" to see processing type code in a finally block.
Maybe you can post your code, and we can suggest a better way for you.