8

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)
}
7
  • 2
    If you switch to VB.NET, you could use On Error Resume Next :-) Dec 9, 2010 at 16:27
  • 1
    Somewhere a VB6/VBA developer is snickering at you. Never thought I'd hear someone pine for "On error resume next"
    – JohnFx
    Dec 9, 2010 at 16:28
  • 2
    @Cody: Oh, God. Oh, God no. Please, no.
    – cdhowie
    Dec 9, 2010 at 16:29
  • 1
    You should be using a tryParse and validating your data. If data has a chance to be invalid, it should be validated, Exceptions are horribly inefficient. Exceptions actually causes a cpu interrupt. Talking about thousands of cycles.
    – Bengie
    Dec 9, 2010 at 17:16
  • @Bengie: I agree that exceptions are slow, I will surely add some validation checks later, i don't want to waste time on optimization for now. Dec 9, 2010 at 17:20

6 Answers 6

13

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);
      }
   }
6
  • 2
    Yes, this is the correct approach, assuming that the sample code from the question accurately depicts the extent of what you want to accomplish with these nested Try-Catch blocks. It's always better to prevent exceptions when possible rather than trying to handle them. Dec 9, 2010 at 16:32
  • 1
    Good answer! +1 for solving the actual problem instead of answering a question about the workaround.
    – JohnFx
    Dec 9, 2010 at 16:33
  • +1 TryParse is the better way to go if you want to ignore parsing errors.
    – juharr
    Dec 9, 2010 at 16:34
  • @BobBlack: well my real code is not so simple as I wrote, so the general aproach with Action<> is better for me. Dec 9, 2010 at 16:37
  • Was just about to suggest this myself but you beat me to it :) Dec 9, 2010 at 17:49
11

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));
3
  • 1
    It's a shame this won't actually compile from typos... :P
    – cdhowie
    Dec 9, 2010 at 16:29
  • @cdhowie, oops, I did not try to compile it, where are the typos?
    – vc 74
    Dec 9, 2010 at 16:31
  • @vc: Action(); -- also, the method should really be static since this is never used.
    – cdhowie
    Dec 9, 2010 at 16:32
4

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));
1

It sound like you're looking for something akin to VBs On Error + Resume Next. C# has no such facility. The best way of compacting I can think of is to use lambda expressions and helper methods.

private void Wrap(Action del) {
  try {
    del();
  } catch (Exception e) {
    Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e);
  }
}

Wrap(() => { NativeObject.Property1= int.Parse(TextObject.Property1); });
Wrap(() => { NativeObject.Property2= DateTime.Parse(TextObject.Property2); });
0

You could write a SafeConvert class that encapsulates the converting and logging as such:

public static class SafeConvert{

  public static int ParseInt(string val)
  {
    int retval = default;
    try 
    { 
       retval = int.Parse(val); 
    } 
    catch (Exception e) 
    { 
        Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e); 
    } 
        return retval;
 }

}

0

Whilst I'm not sure about the Exception block shortening, I like the idea you've proposed. It's similar to On Error Resume Next in VB of old. When doing loads of Parse-ing, I'd go down the route of using TryParse when it's available. You could then say something like:

If(!DateTime.TryParse(TextObject.Property2, out NativeObject.Property2)) {
    // Failed!
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.