Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compact lots of small Try-Catch blocks when handling exceptions in C#?

In my object conversion code I have tons of:

    try
    {
        NativeObject.Property1= int.Parse(TextObject.Property1);
    }
    catch (Exception e)
    {
        Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e);
    }
    try
    {
        NativeObject.Property2= DateTime.Parse(TextObject.Property2);
    }
    catch (Exception e)
    {
        Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e);
    }

And so on... I do not want all conversion to fail cause of some property so I can't put all this in one try block, but I need to log if something fails and continue..
Is there a way to compact all this try catch things?

Pity we can't write in C# code like:

try
{
    int num = int.Parse("3");
    decimal num2 = decimal.Parse("3.4");
}
catch (Exception e)
{
    Trace.Write(e);
    continue; //continue execution from the point we left. (line 2)
}
like image 877
Alex Burtsev Avatar asked Dec 09 '10 16:12

Alex Burtsev


3 Answers

You could use the TryParse methods, when available. See below sample code for parsing an Int32 value.

   private static void TryToParse(string value)
   {
      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }
like image 107
Bob Black Avatar answered Oct 31 '22 09:10

Bob Black


No but you can:

private static void ExecuteAndCatchException(Action action)
{
  try 
  { 
    action();
  } 
  catch (Exception e) 
  { 
    Trace.Write(e); 
  } 
}

and then

ExecuteAndCatchException(() => NativeObject.Property1 = int.Parse(TextObject.Property1)); 
ExecuteAndCatchException(() => NativeObject.Property2 = DateTime.Parse(TextObject.Property2));
like image 24
vc 74 Avatar answered Oct 31 '22 08:10

vc 74


You could do something like this:

private static void Attempt(Action action)
{
    try { action(); }
    catch (Exception e) {
        Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e);
    }
}

Then:

Attempt(() => NativeObject.Property1 = int.Parse(TextObject.Property1));
Attempt(() => NativeObject.Property2 = DateTime.Parse(TextObject.Property2));
like image 33
cdhowie Avatar answered Oct 31 '22 09:10

cdhowie