I have a section of code that I have encased in a try-catch block. I did this because I wasn't getting the results that I expected. But now, I'm not getting the results I expect out of a try-catch block.
My understanding is that the code in the try block is executed. If an exception is thrown, the catch block catches it, and then the code moves on.
What I am seeing is the code in the try block throwing an exception. Then the catch block catches it, and sends me an email with the exception ToString()
. But then, the code in the try block continues where it left off. I didn't think that it would pick back up where it left off. I thought it was done.
Here is some psudo code of what I am doing:
try
{
var context = New DbContext();
for(var i = 0; i < 5; i++)
{
var records = ABunchOfRecordsThatIGather(OneHundredAtATime);
foreach(var record in records)
{
context.Add(record);
}
context.SaveChanges();
context.Dispose();
context = New DbContext();
}
SendMeASuccessEmail();
}
catch (Exception ex)
{
SendMeAnEmailOfTheException(ex.ToString());
}
I'm getting a variety of errors (a different question), but some of them are System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint
errors, and some of them are A transport-level error has occurred when receiving results from the server
ish errors.
Regardless, if I get the error after inserting 100 records (and need to insert 500), I would not expect to see the error after 100 (I have a counter that I email myself too), and then the success email after it finishes up. But, that is what I am seeing. I get both an error email and a success email later.
Can anyone clarify this for me?
EDIT:
Since the comments pretty much went off topic, I will edit my PSUDOcode to hopefully nip that in the bud. Here goes:
try
{
DoSomeEntityFrameworkStuff();
SendASuccessEmailIfAllIsWell();
}
catch
{
SendAFailureEmailIfSomethingBadHappens();
}