C# Error CS0157 – Control cannot leave the body of a finally clause

C# Compiler Error

CS0157 – Control cannot leave the body of a finally clause

Reason for the Error

You will receive this error when you have used the return statement inside the finally block.

The below code snippet demonstrates the C# error code CS0157 as it uses the return keyword with-in the finally block.

namespace ConsoleApp2
{
    class Program
    {
        public static void Main()
        {
            try
            {
 
            }
            finally
            {
                return;
            }          

        }

    }
    
}
C# Error CS0157 – Control cannot leave the body of a finally clause

Error CS0157 Control cannot leave the body of a finally clause ConsoleApp2 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp2\Program.cs 19 Active

Solution

C# specifies that all the statements inside the finally clause must execute. Having the return statement will break this rule. You will need to remove the return statement inside the finally block to fix this error.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...