简体   繁体   中英

In .NET, what if something fails in the catch block, will finally always get called?

In a try/catch/finally block like:

try
{

}
catch()
{
   // code fails here
}
finally
{ 

}

So if there is an exception in the catch block, will finally always get called?

What if there is no finally, will the code after the catch block get run?

Assuming the process doesn't terminate abruptly (or hang, of course), the finally block will always be executed.

If there's no finally block, the exception from the catch block will just be thrown up the stack. Note that the original exception which caused the catch block to be executed in the first place will be effectively lost.

Stack overflow exceptions

As Jared noted, a stack overflow will cause the finally block not to be executed. I believe this terminates the program abruptly, but I could be wrong. Here's sample code:

using System;

public class Test
{    
    static void Main()
    {
        // Give the stack something to munch on
        int x = 10;
        try
        {
            Main();
            Console.WriteLine(x);
        }
        finally
        {
            Console.WriteLine("Finally");
        }
    }  
}

Results:

Process is terminated due to StackOverflowException.

The finally block will always get executed. If you exclude the finally block, and an exception occurs inside the catch block, then no code after the catch block will execute, because essentially you're catch block will fail and generate an unhandled exception itself.

Yes the finally will always be run

No the code after the catch block won't be run.

Even with a finally block any code following the finally block will not run.

If there's an exception in the catch block, the finally will execute, but a new exception will be thrown. The catch block in which the exception occurred will not catch the exception, it will continue up the stack.

Lesson learned: don't do stuff in the catch block that can throw if you can help it; if you must, nest a try/catch block.

try
{

}
catch()
{
  try
  {
    // code fails here
  }
  catch
  {
    // handle that. Or not. 
  }
}
finally
{ 

}

The finally block will always be executed. From MSDN :

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

By the way, this is the type of question that you can easily test yourself by writing some code, compiling it, and seeing what happens when you execute it.

class Program {
    static void Main(string[] args) {
        try {
            Console.WriteLine("Trying!");
            throw new Exception();
        }
        catch (Exception e) {
            Console.WriteLine("Catching {0}!", e.Message);
            throw new Exception();
        }
        finally {
            Console.WriteLine("Finally!");
        }
    }
}

This outputs:

Trying!
Catching Exception of type 'System.Exception' was thrown.!

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was
thrown.
at TestFinally.Program.Main(String[] args) in C:\Documents and Settings\Me\My
Documents\Visual Studio 2008\Projects\TestFinally\TestFinally\Program.cs:line 15
Finally!
Press any key to continue. . .

Just wanted to add the cases I'm aware about that will not allow the finally and any other code block execute:

  • In case of a runtime-thrown StackOverflowException
  • System.Environment.FastFail
  • Environment.Exit
  • If a "background" thread is terminated because the main program to which it belongs is ending.
  • Unexpected Shut Down:)

If an exception occurs in the catch block, all the code in finally would still be executed. If there is an exception handler higher up in the stack (eg caller of this function), it will catch this exception. Else result in an unhandled exception and bring your app down.

The code after the point of exception in the catch block will not get called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM