开发者

try catch finally question

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 that the finally block only executes if the catch block passes without errors. If the catch block is executed because of an error, shouldn't it stop execution all togeth开发者_开发百科er and return the error message if any?


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...


Not only will a finally block execute following a catch block, try does not even require that any exception be caught for the finally to execute. The following is perfectly legal code:

try 
{
//do stuff
}
finally 
{
   //clean up
}

I actually took out the catch blocks in some code I inherited when the catch block consisted of:

catch(Exception ex)
{
   throw ex;
}

In that case, all that was required was to clean up, so I left it with just a try{} and finally{} block and let exceptions bubble up with their stack trace intact.


the finally block executes in almost every case. That's why it's called 'finally'.

For an example, see this article on c-sharpcorner.com.

Update: It's true, if you plug the cable, melt the processor or grind the motherboard, even the most final 'finally' will not be executed.

But in almost every 'normal' scenario, i.e. wether your code throws an exception or not, the finally block will be executed. To my knowledge the only 'real' exception to this rule is a stackoverflow exception which will terminate the program w/o entering finally.

Update 2: This question was asked specifically for C#. This answer is NOT covering Java, Python, Matlab or Scheme.


The finally block will execute, but you'll need to be careful of exceptions within the finally block.

try {
   // some disposable method "o"
} finally {
  o.Dispose(); // if o is null, exception is thrown
   // anything after this exception will fail to execute
}


The code inside the finally block gets always executed, regadless if there was an exception. By the way, I think there are already numerous threads on SO that deal with this question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜