Wednesday, July 11, 2007

Catch Block Error Handling

Shows a good way to handle errors that may occur inside the catch block, for example while logging the original error.

Please note that logging and emailing are used as examples for the catch block processing just for demonstrating the concept; but it could equally apply to any call inside the catch block that can throw exceptions.

[C#]

// ----------------------------------------------
// From: http://coding-help.blogspot.com/
// Title: Catch Block Error Handling
// Date: 11 July 2007
// Author: R. K. Wijayaratne
// Description: Shows a good way to handle errors
// that may occur inside the catch block, for
// example while logging the original error.
//
// Please note that Logging and emailing are used
// as examples for the catch block processing
// just for demonstrating the concept; but it
// could equally apply to any call inside the
// catch block that can throw exceptions.
//
// To Run: Create a new C# file, e.g. "Program.cs",
// copy and paste the code below into it and save.
// To compile it open the .NET Framework command
// prompt and type:
//
// csc C:\MyPath\Program.cs
//
// where "C:\MyPath\" is the path of the C# file.
// If there are any errors correct them. To run
// the program type "Program" and press "Enter."
// ----------------------------------------------

using System;

public class Tester
{
  // Program entry point.
  static void Main(string[] args)
  {
    // Start running the test.
    Tester.StartTest();
  }

  // Test driver method.
  public static void StartTest()
  {
    try
    {
      // Test error handling.
      TestHelper.TestErrorHandling();
    }
    catch (Exception exc)
    {
      // Write errors to console.
      Console.Write(exc.ToString());
    }
  }
}

public class TestHelper
{
  public static void TestErrorHandling()
  {
    try
    {
      // Try to do some work.
      // Doing some work...
      // Simulate error.
      throw new InvalidOperationException();
    }
    catch (InvalidOperationException invOpExc)
    {
      string errDesc = "An invalid operation"
      + " occurred while doing some work.";
      string extraErrs = null;
      bool handled = true;

      try
      {
        // Try to log original error.
        // Logging original error...
        // Simulate new error.
        throw new SystemException();
      }
      catch (SystemException sysExc)
      {
        handled = false;
        extraErrs += "\n\nAdditional error"
        + " occurred while"
        + " logging:\n\n"
        + sysExc.ToString();
      }

      try
      {
        // Try to email original error.
        // Emailing original error...
        // Simulate new error.
        throw new ArgumentException();
      }
      catch (ArgumentException argExc)
      {
        handled = false;
        extraErrs += "\n\nAdditional"
        + " error occurred"
        + " while emailing:\n\n"
        + argExc.ToString();
      }

      // Throw it up to caller if not handled.
      if (!handled)
      {
        errDesc = string.Format("{0}\n====="
              + "{1}\n\n=====\n",
              errDesc, extraErrs);

        throw new Exception(errDesc, invOpExc);
      }
    }
  }
}

Console Output

System.Exception: An invalid operation occurred while doing some work.
=====

Additional error occurred while logging:

System.SystemException: System error.
at TestHelper.TestErrorHandling()

Additional error occurred while emailing:

System.ArgumentException: Value does not fall within the expected range.
at TestHelper.TestErrorHandling()

=====
---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at TestHelper.TestErrorHandling()
--- End of inner exception stack trace ---
at TestHelper.TestErrorHandling()
at Tester.StartTest()


Also See

  1. See 'Exception' (on MSDN) here http://msdn2.microsoft.com/en-us/library/5b2yeyab.aspx

No comments: