Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
Blankman Avatar asked Feb 24 '09 15:02

Blankman


People also ask

What if error occurs in catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

Does a Finally block always get executed in C#?

A finally block always executes, regardless of whether an exception is thrown.

Is finally block called after catch?

The finally block will in fact run after the catch block (even if the catch block rethrows the exception), which is what my snippet is trying to illustrate.

Will finally block executed if the catch block executed?

A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code. We cannot say the finally block is always executes because sometimes if any statement like System.


2 Answers

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.

like image 62
Jon Skeet Avatar answered Oct 07 '22 13:10

Jon Skeet


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.

like image 29
Joseph Avatar answered Oct 07 '22 13:10

Joseph