Return value from a method if the method throws an exception
.net, c#, exception
Solution
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.
Problem
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`?