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);
}
}
It's not possible to both throw an exception and return a value from a single function call. Perhaps it does something like returning false if there's an error, but throwing an exception if the input is invalid.
You do not need to put a return statement after throw , the return line will never be reached as throwing an exception immediately hands control back to the caller.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With