Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement after throwing an exception in C#

Tags:

c#

dictionary

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); 
        }
    } 
like image 357
Faisal Mansoor Avatar asked Mar 02 '11 20:03

Faisal Mansoor


People also ask

Can you throw an exception and return something?

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.

Do you need to return after throw?

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.

What happens after throwing an exception?

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.

Does throwing an exception exit the method?

When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.


2 Answers

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.

like image 119
John Gietzen Avatar answered Sep 22 '22 23:09

John Gietzen


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.

like image 34
Matt Greer Avatar answered Sep 23 '22 23:09

Matt Greer