Another interview question which was expecting a true / false answer and I wasn't too sure.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Generally the
finally
block is guaranteed to execute.However, a few cases forces the CLR to shutdown in case of an error. In those cases, the
finally
block is not run.One such example is in the presence of a StackOverflow exception.
E.g. in the code below the
finally
block is not executed.The other case I am aware of is if a finalizer throws an exception. In that case the process is terminated immediately as well, and thus the guarantee doesn't apply.
The code below illustrates the problem
In both cases the process terminates before both
catch
andfinally
.I'll admit that the examples are very contrived, but they are just made to illustrate the point.
Fortunately neither happens very often.
'Finally' is executed regardless of whether an exception is thrown or not.
Its a good place to close any open connections. Successful or failed execution, you can still manage your connections or open files.
Yes, finally is always executed.
It is not totally true that finally will always be executed. See this answer from Haacked:
However, these two exceptions are exception you cannot recover from, so basically your process will exit anyway.
As mentioned by Mehrdad, a reliable try/catch/finally will have to use Constrained Execution Regions (CER). An example is provided by MSDN: