try catch finally question

前端 未结 5 855
你的背包
你的背包 2020-11-29 08:34

In a Try Catch Finally block, does the finally block always execute no matter what, or only if the catch block does not return an error?

I was under the impression

5条回答
  •  庸人自扰
    2020-11-29 09:13

    The finally block (nearly) always executes, whether or not there was an exception.

    I say nearly because there are a few cases where finally isn't guaranteed to be called:

    • If there is an infinite loop or deadlock in your code so that the execution remains inside the try or catch blocks then the finally block will never execute.
    • If your application is terminated abruptly by killing the process.
    • Power cut.
    • Calling Environment.FailFast.
    • Some exceptions such as:
      • StackOverflowException
      • OutOfMemoryException
      • ExecutingEngineException (now obsolete)
    • An exception thrown in a finalizer (source).

    Furthermore, even if the finally block is entered if a ThreadAbortException occurs just as the thread enters the finally block the code in the finally block will not be run.

    There may be some other cases too...

提交回复
热议问题