13 September 2015

avoiding the execution of finally block of code in C# .NET

We all know that finally block of code is always going to get executed irrespective of whether there is an exception or not. Thereby finally() block of code helps to clean any resources held up by the code.

But, there is one exception to the above rule.

The finally block of code will not get executed, when the code executes Environment.FailFast() method.

static void Main(string[] args)
{       
  try
  {
    Environment.FailFast("Message logged!");
  }
  catch (Exception ex)
  {
                    
  }
  finally
  {
    Console.WriteLine("finally executed...");
  }
}

Whenever Environment.FailFast() method gets executed, it immediately terminates a process after it writes the message to the Windows Application Event log!

You can see the below error logged into Windows Application log.

Application: FailFast.exe Framework Version: v4.0.30319 Description: The application requested process termination through System.Environment.FailFast(string message). Message: Message logged! Stack: at System.Environment.FailFast(System.String) at FailFast.Program.Main(System.String[])

No comments:

Post a Comment