C# Exception handling versus return error from method result

Thursday, July 10, 2014

I am developing some c# classes or better said components. They are nested quite deep one within another and anything can go wrong at any step.


So I can have class A that calls a method on class B that can call methods on classes C and D. Now something can go wrong in any of these classes, except for class A which is responsible for handling any errors that happen during processing to alert the user and generate a proper response for the processing.


Now the problem is that I do not know which approach to use. I can use exceptions and catch them in the top level class A or return individual results from each method that is called on nested classes that contain information if the process was successful or not. This would be the most convenient because all I need is to catch exception on the top level class. On the other hand this might be slow. This can happen like 100 times each minute and even 10 times per second.


So using the approach above my class A would look like:



public class A
{
private ILog _logger = ObjectFactory.GetInstance<ILog>();

public void ProcessMethod()
{
try
{
var b = new B();
b.Process();
}
catch(ProcessException ex)
{
_logger.Debug(ex.Error);
}
}
}


Or I can use to return from the method if the execution was successful. I am trying to avoid this because it is more work and harder to maintain:



public class A
{
private ILog _logger = ObjectFactory.GetInstance<ILog>();

public void ProcessMethod()
{

var b = new B();
var result = b.Process();
if (result.HasError)
{
_logger.Debug(result.Error);
}
}
}






http://ift.tt/1rWD3gK