Reputation: 2041
The following function from Systems.Collections.Generic.Dictionary class has return statement after throwing an exception, does any one have any idea why?
public TValue this[TKey key] {
get {
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
**return default(TValue);**
}
set {
Insert(key, value, false);
}
}
Upvotes: 6
Views: 1510
Reputation: 49544
Even though the
ThrowHelper.ThrowKeyNotFoundException();
Certainly does throw an exception, the compiler is not sophisticated enough to prove that it will never do anything else. And since it cannot prove that the function never returns, it has to assume that it could return.
Eric Lippert just finished a mini-series on his blog entitled "Never Say Never" about this very issue.
http://blogs.msdn.com/b/ericlippert/archive/2011/02/21/never-say-never-part-one.aspx
It turns out that this is a simple case of the Halting Problem, which has been shown to be undecidable over Turing Machines.
Upvotes: 7
Reputation: 62027
It is forced to, because the method itself is not directly throwing, the ThrowHelper is. The compiler has no way of knowing this, so to satisfy the compiler the return default(TValue);
is added, even though it will never get invoked.
Upvotes: 3