Reputation: 8791
It's Monday again and I have a question about C# basics. What happens to the return value from a method if the method throws an exception?
Specifically, what is happening "under the hood" when an exception is being thrown inside a method and what effect does that have on the return value? In this situation, how is the return value calculated internally?
Let's say there are two scenarios: one where the return value is of type int
and another of type object
. Is default(T)
going to be called internally when an exception occurs? In such a case, should I consider that the return value of type int
is zero while the return value for an object is null
?
Upvotes: 11
Views: 4529
Reputation: 10478
The short, oversimplified answer is that it won't return anything. Code "breaks" wherever the exception occurs and it goes down the stack until something catches it.
Even if you do happen to catch the exception, the variable you tried to initialize with the method's return value will remain what it was before the method was called:
var i = 5;
try
{
i = MyMethodThatThrowsAnException();
}
catch
{
// at this point, the i variable still equals 5.
}
I should mention that you really shouldn't feel concerned about the function's return value if it throws an exception. If you do, then likely you're doing something wrong, like using exceptions as flow control.
Upvotes: 14
Reputation: 109567
To make a major simplification:
When an exception is thrown, the .Net CLR starts searching back up the stack until it finds an exception handler that can handle the exception.
At that point, the stack pointer is adjusted so that the exception handling code is run with the correct parameter from the correct point. (The exception itself captures the stack information at the throw-point to make that information available at the catch-point.)
Effectively, the CLR has performed a kind of "goto" which jumps past any code which may have been using any return value from the function which threw the exception - so the return value is simply not relevant. It is never created, used, or needed in this scenario.
Please note that this is a vast simplification of what actually happens, but the main point to take away is that a complicated kind of goto - which traverses stack frames - occurs. That's what makes the return value irrelevant.
See this article for full details.
Upvotes: 3