While working on a project, I have found some behaviour that neither I nor my colleagues are able to explain. The code used is simplified below:
public Foo DoSomethingWithFoo()
{
Foo foo;
try
{
foo = GetFoo();
}
catch (Exception e)
{
DbHandler.LogException(e);
throw;
}
return foo;
}
This compiles perfectly fine, but as soon as we remove the throw;
statement. We get a compilation error: Use of unassigned local variable 'foo'
The problem is not to resolve it, as we can just write Foo foo = null;
.
We understand that in C# local variables have no default value, which is different than being assigned null. It's just that we can't seem to figure out why removing the throw statement causes this behaviour. Although I did find some more information about undefined variables, I haven't found anything (yet) to explain this.
So what is the explanation behind this?