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)
}
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);
}
}
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));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With