Exception Handling Question?

Topics: Exception Handling Application Block
Jun 29, 2007 at 8:21 PM
Microsoft's typical pattern works well if the method doesn't return anthing:

public void ProcessSomething()
{
try
{
//Do something that might throw SomeException
ProcessSomething();
}
catch(SomeException ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "Some Policy");

if(rethrow)
throw;
}
}


Microsoft's typical pattern doesn't work so well with a method that return something:

This method will not complie because not all code paths return a value due to the if(rethrow) statement.
To make this complie you would have return some dummy Int32 at the end of the method.

public Int32 ReturnSomething()
{
try
{
//Do something that might throw SomeException
return GetSomething();
}
catch(SomeException ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "Some Policy");

if(rethrow)
throw;
}
}


Is there a better pattern or do I need to create dummy return values?
Jul 2, 2007 at 3:04 PM
Hi,

I don't think there is a "one size fits all" recommendation for this. The return values and the exceptions you throw are part of your method's contract, so you need to decide what the return value should be when you don't rethrow the exception. Returning a default value may or may not be the best approach; keep in mind that it's very likely that the caller of the method will use the return value as it doesn't know that an exception was caught and not rethrown.

Fernando
Jul 3, 2007 at 5:31 PM
Hello!
In my opinion, this is what you want:

public int ReturnSomething
{
int result = 0;
try
{
// some code here
// ...

// last line in try block:
result = GetSomething();
}
(catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "Some Policy");
if (rethrow)
{
throw;
}
}
return result;
}



Jul 4, 2007 at 2:08 PM
Hi,

While this would let the code build, it may or may not be the right solution. As I mentioned before, it would only be correct if returning 0 when an exception is not rethrown is appropriate for the contract implemented by the method. The method caller would not be aware of the exception that was thrown and handled, so it will accept the return value as valid; I don't think there are many cases where a fixed value is the right value to return every single time an exception is caught and handled by the EHAB.

Just my $.02...

Regards,
Fernando


hendrikhalkow wrote:
Hello!
In my opinion, this is what you want:

public int ReturnSomething
{
int result = 0;
try
{
// some code here
// ...

// last line in try block:
result = GetSomething();
}
(catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "Some Policy");
if (rethrow)
{
throw;
}
}
return result;
}