V
V
Vadim Nikiforov2022-03-07 15:21:01
.NET
Vadim Nikiforov, 2022-03-07 15:21:01

Try and Finally - What will the function return?

What will happen in my opinion
If ... somecode ... in this block (try) did not raise an exception, then after its execution it will exit the function on the return operation and return false. If, however, an exception occurs in the try block, the normal execution order stops and the CLR starts looking for a catch block that can handle the exception. If the desired catch block is found, then it is executed, and after its completion, the finally block is executed. If the required catch block is not found, then the program crashes when an exception occurs.

Code:

bool f() { 
    try {
        ...somecode…
  return false; // Если не возникло исключений, то после его выполнения он выйдет из функции на операции return и вернет false?
    } finally {
  ...some code…
  return true; // Если возникло исключений и нужный блок catch найден и тогда выполниться finally вернет true?
    }
}


Are my statements correct?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2022-03-07
@nikifovadim

Your code won't compile :)
You can't put return in the finally block.
https://docs.microsoft.com/en-us/dotnet/csharp/mis...
And in general, yes - finally is executed in any case, even if an exception has not been thrown.

H
HemulGM, 2022-03-07
@HemulGM

finally will be executed anyway. This is its meaning
Read the documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question