Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from a method if the method throws an exception

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?

like image 517
dev hedgehog Avatar asked Mar 24 '14 12:03

dev hedgehog


People also ask

What does a method return if it throws an exception?

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.

Can you throw an exception and return a value?

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 throwing an exception Java?

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.

Do you need to return after throwing an exception?

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.


1 Answers

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.

like image 182
Crono Avatar answered Sep 21 '22 02:09

Crono