I have a section of code that looks like this:
try
{
classVar = functionCall(input, sEnum.First);
classVar = functionCall(input, sEnum.Second);
classVar = functionCall(input, sEnum.Third);
}
catch (Exception ex)
{
Debug.Assert(false, ex.ToString());
}
However my exception dosent show which specific call it came from. The stack trace also only shows details from another class called from inside the function call.
The alternative way to wrap this is:
try
{
classVar = functionCall(input, sEnum.First);
}
catch (Exception ex)
{
Debug.Assert(false, ex.ToString());
}
try
{
classVar = functionCall(input, sEnum.Second);
}
catch (Exception ex)
{
Debug.Assert(false, ex.ToString());
}
try
{
classVar = functionCall(input, sEnum.Thrid);
}
catch (Exception ex)
{
Debug.Assert(false, ex.ToString());
}
Though I think it is much less readable that the previous version.
Is there a pattern for wrapping the function calls or passing off the exceptions in such a way that i can later see where they came from while keeping the code readable?
Option 1
Change functionCall()
to re-throw a custom exception with contextual information. Catch the exception at a higher level for logging, calling Debug.Assert
, etc.
Option 2 This pattern can provide reuse of exception handling logic at a slight loss in readability. Caution: over-use of delegate techniques at the cost of clarity can become a code smell.
static void InvokeActionWithContext(Action action, string description) {
try
{
action();
}
catch(Exception ex)
{
throw new AnExceptionWithContext(description, ex);
}
}
// call like this
InvokeActionWithContext(
() => classVar = functionCall(input, sEnum.Third),
"Initializing value three"
);