0

In the following code I have a nested Try Catch. In the case where my nested catch fails I want to just to the parent catch statement and execute that code. How can i do this?

try
  {
    try
    {   // build and send invoice lines
      ReadInvLinesToArray(row["ID_INVOICE"].ToString());
    }
    catch (Exception e)
    {
      writeToEventLog(e.ToString(), true, false);
      SendErrorEmail("Failed to send Invoice Lines to NAV.  The following system error was generated: \n" + e.ToString());
    }
    // send invoice header if lines have been sent
    bool result = navInvoices.SendInvoicesToNAV(navImportInvoices);
    // update the retrieved records, marking QB Status as value N, passing in the sql dataset as a list        
    UpdateQBStatusInvoiceSent(ref idInvoicesSent);
  }
catch (Exception e)
  {
  // remove Invoice from list to ensure its status is not updated.
  idInvoicesSent.Remove(Convert.ToInt32(row["ID_INVOICE"]));

  WriteToEventLog(e.ToString(), true, false);
  SendErrorEmail("Failed to send Invoices to NAV.  The following system error was generated: \n" + e.ToString());
  }
Gavin
  • 437
  • 2
  • 8
  • 20
  • 2
    What do you mean fails? You mean an exception is thrown in the inner catch? If that happens then the flow goes to the outer catch to handle that exception But in the outer catch you're running the same 2 statements as the inner catch, so if the inner fails, why would the outer not fail as well? – KMoussa Oct 06 '16 at 16:08
  • The outer exception will undo some modifications to the database. The inner try catch works with child records whilst the outer handles the Parent records. If the inner fails then i need to roll back my parent record modifications. I will amend the email being sent. – Gavin Oct 06 '16 at 16:13

1 Answers1

3

You CAUGHT the exception with that "inner" catch, so the exception has been deal with it. If you want the "outer" catch to trigger as well, you'd have to RE-THROW the exception:

try {
   try {
     ...
   } catch (Exception e) {
      ... do stuff
      throw e; // you need this
   }
} catch (Exception e) {
   ... catch the re-thrown "e"
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 2
    Why not just `throw`, as per [this question](http://stackoverflow.com/questions/22623/best-practices-for-catching-and-re-throwing-net-exceptions)? – stuartd Oct 06 '16 at 16:09
  • Excellent. Thanks very much. I'll accept in 9 minutes. I don't see why must question was voted down. – Gavin Oct 06 '16 at 16:09
  • Marc, my nested try catch has code which happens after that, but still in the scope of the parent try. I use throw in my nested catch. Will this jump out to the parent catch immediately, or execute the code which is after the nested (throwing) catch, but still in the try? My code line bool result = navInvoices.SendInvoicesToNAV(navImportInvoices); still seems to be executing. – Gavin Oct 07 '16 at 15:53