Gavin Gavin - 2 months ago 7
C# Question

How to escape from a nested Catch statement

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());
}

Answer

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"
}