0

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 serverish 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();
}
FlipperBizkut
  • 423
  • 1
  • 5
  • 15
  • 3
    This can't be true. You might be calling it from somewhere else as well, try putting the breakpoints before & after on the line which throws the exception and see does it starts after the exception line – Ali Baig Jan 29 '17 at 21:07
  • 2
    Is your function tied to an asynchronous request (client-side) somewhere, and it's getting multiple times, perhaps through a timer or a client-side event? – Matt Spinks Jan 29 '17 at 21:11
  • @AliBaig I couldn't agree more, but it is true. Totally confounding. I have no way to debug on the production environment (where this is happening), and it works perfectly on the development servers. I thought that possibly something in EntityFramework was allowed to throw exceptions that were separate from everything else. That is the only idea I have to maintain my sanity. That, or I'm actually at the point of thinking there may be hardware failure causing chaos (bad ram or something else flipping random bits). – FlipperBizkut Jan 29 '17 at 21:16
  • @MattSpinks Nope. In fact, I wanted to eliminate all those possibilities, so I have it to where I click a button, it calls a function, that's it. No other routing, no async, no nothing. Totally boring. Totally predictable (I thought). – FlipperBizkut Jan 29 '17 at 21:19
  • The way you manage the `DbContext` is awful, and possibly a source of some errors and confusion. Do look for an example with a `using(){}` block. – H H Jan 29 '17 at 22:20
  • @HenkHolterman why is it awful? – FlipperBizkut Jan 29 '17 at 22:24
  • Why are you creating a new `DbContext` each time through the loop? – Chris Dunaway Jan 29 '17 at 23:52
  • See http://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework/5942176#5942176 – FlipperBizkut Jan 30 '17 at 00:55
  • The whole `try`/`catch` like that is a bad anti-pattern. Have a read of [Eric Lippert's Vexing Exceptions](https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/). – Enigmativity Jan 30 '17 at 02:42
  • You will at least leave the last context open. They are not properly managed, you really need a `using(){}` – H H Jan 30 '17 at 07:08
  • @HenkHolterman I assure you that if properly disposed, using a `using()` statement is not mandatory. Even so, it has absolutely nothing to do with the original question. @Enigmativity I assure you that I am only catching everything since I had no idea what was being thrown. This works fine on my development server, and I have no access to debugging software on my production server. Wrapping the method in a try-catch block was the first and easiest thing I could do to see why the craziness was occurring. And, not to be ungrateful, but again has nothing to do with the original question. – FlipperBizkut Jan 30 '17 at 21:42
  • 1
    You'll get two mails if `SendASuccessEmailIfAllIsWell` itselfs throws an uncaught exception after having sent an email successfully *and* runs in a thread that happens to lag behind the thread in `SendAFailureEmailIfSomethingBadHappens`. All in all, quite "exceptional", but the only thing I can think of. – Gert Arnold Jan 30 '17 at 22:28
  • I notice the mention of 'pseudo code' in the question. But that also throws a lot of doubt on the main issue. Also, when it's on a server you probably (can) have multiple requests/threads going on etc. – H H Jan 31 '17 at 07:28
  • The main issue (as the title suggests) is a quick sanity check on how entity framework behaves inside a try catch block. I posted the question because I was getting the result from the catch block, and then afterwards, getting the success result too. That is contrary to how I believed it to work, so I posted. @Henk, you have posted nothing useful whatsoever regarding the question at hand, but have instead picked apart everything else that matters not. In fact, the answer posted, and the first two comments are the only thing even relevant to the original question. Thanks for nothing. – FlipperBizkut Jan 31 '17 at 23:28
  • One last thing @HenkHolterman... even if the code in the try block was written by an 11 month old monkey, what difference does that make? If an exception is thrown, the catch catches it, and moves on. Right? That's what I want to know. It should _never_ take back off in the try where it threw after going to the catch. In other words, once it goes into the catch block, it can never go back into the try. Correct? – FlipperBizkut Jan 31 '17 at 23:33

1 Answers1

0

The code will not pick up where it left off after an exception.

Based on Your psudo code I would suggest 3 possibilities / Things you could check:

  1. Are there async Calls, so the exception is occuring after the code has executed subsiquent lines
  2. Is Your send success email inside a for loop, so that you get that email before the program is Complete
  3. Do you have multiple try Catch Blocks, in that case the exception could have been "swallowed" by an inner try Catch Block.
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
  • Only one try catch block. The entire method is the try catch. No async calls. The send email methods are the final things in the code (only thing in the catch, final line of the try). It really makes no sense whatsoever to me (which is why I posted here). – FlipperBizkut Jan 29 '17 at 22:21
  • Marked as answer since this is the only answer provided, and it is at least helpful in troubleshooting. – FlipperBizkut Feb 01 '17 at 21:21