The return value from the method if the method throws an exception

Monday again, and I have a question about the basics of C #. What happens to the return value of a method if a method throws an exception?

In particular, what happens “under the hood” when an exception is thrown inside the method and what effect does it have on the return value? In this situation, how is the internal return value calculated?

Let's say there are two scenarios: one where the return value is of type intand the other is of type object. Is it default(T)called internally when an exception occurs? In this case, should we assume that the return value of the type intis zero, and the return value for the object is null?

+4
source share
2 answers

The short, simplified answer is that it will return nothing . The code breaks wherever an exception occurs and it flows down the stack until something catches it.

Even if you really catch the exception, the variable that you tried to initialize with the return value of the method 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 should not worry about the return value of a function if it throws an exception. If so, then you are probably doing something wrong, for example, using exceptions as flow control .

+8
source

:

, CLR.Net , , .

, . ( , .)

, CLR "goto", , , , , , . , .

, , , , , - , goto - . , .

. .

+2

Source: https://habr.com/ru/post/1533153/


All Articles