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
?
No matter what type you return, that type will not be returned, because you are throwing an exception (which indicates something wrong happened) on the first line. The compiler allows this because throwing an exception means something wrong happened, like the arguments are invalid, or the argument is null, and so on.
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.
Can you return after a throw? After you call throw the method will return immediately and no code following it will be executed. This is also true if any exceptions are thrown and not caught in a try / catch block.
After throwing an exception, you do not need to return because throw returns for you. Throwing will bubble up the call stack to the next exception handler so returning is not required.
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.
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