visual studio failed to detect code return path
I experienced on when refactoring some code, maybe I'm blind but I failed to see why the following code won't work.
public bool Foo()
{
try
{
return SomeFunctionMightThrow();
}
catch (Exception ex)
{
Logger.log开发者_如何学Python(ex);
throw ex;
}
}
So far so good, if I refactor code to
public bool Foo()
{
try
{
return SomeFunctionMightThrow();
}
catch (Exception ex)
{
LogAndThrow(ex);
}
}
private void LogAndThrow(Exception ex)
{
Logger.log(ex);
throw ex;
}
Code does not compile now.
You could potentially change it to...
public bool Foo()
{
try
{
return SomeFunctionMightThrow();
}
catch (Exception ex)
{
// note: this will reset the exception stack trace
throw LogAndReturnException(ex);
}
}
private Exception LogAndReturnException(Exception ex)
{
Logger.log(ex);
return ex;
}
This essentially does exactly what you want but gives VS the code return path.
Or for a more simplistic approach which will retain the stack trace, just change your catch to:
catch (Exception ex)
{
Log(ex);
throw; // retains stack trace
}
The compiler doesn't take into account that your LogAndThrow()
method always will throw an exception - that being the case all code paths in Foo()
must return a boolean, so you could just do this:
public bool Foo()
{
try
{
return SomeFunctionMightThrow();
}
catch (Exception ex)
{
LogAndThrow(ex);
return false; //will never get here
}
}
In general since you throw anyway I would recommend using a try/catch
block at a single central spot in your app for logging, i.e. at the highest level unless you can really handle the exception - it doesn't look like you are here.
精彩评论