BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 2.0+

Using Environment.FailFast

When an application becomes critically unstable, it is sometimes better to exit, rather than risk corruption. If even exiting normally could cause damage to data, it is appropriate to ignore any exception handling and stop the process immediately.

Critical Failures

Some software generates the risk that a process can enter an unstable state that introduces the risk of data corruption. For example, you might be dealing with large amounts of data and run out of memory. If this means that it is not possible to continue with the process safely, it may be necessary to exit the program and report an error.

Depending upon the software being executed, you may find that exiting causes other code to run. This could be part of the normal flow or may be code within catch or finally blocks. In some situations, exception handling code may try to update information in a file or database. If this uses corrupt information it may damage your user's work. In this case it is better to kill the process immediately, ensuring that no further code executes. This is possible using the FailFast method of the Environment class, which is found in the System namespace.

Environment.FailFast

The FailFast method stops your program immediately, ensuring that no further code can execute. As this means that you cannot report the problem directly to the user, this static method includes a parameter, to which you can provide a string containing a status message. This message is recorded in the application event log.

To demonstrate, create a new console application project and add the following code to the Main method. The code includes commands to output four messages to the console. The first is displayed before the call to Environment.FailFast. As FailFast exits the program straight away, the following messages within the try, catch and finally blocks are not shown.

try
{
    Console.WriteLine("Start");
    Environment.FailFast("Goodbye, cruel world!");
    Console.WriteLine("End");
}
catch
{
    Console.WriteLine("Catch Block");
}
finally
{
    Console.WriteLine("Finally Block");
}

Try running the code without debugging by pressing Ctrl-F5. You'll see just the "Start" message before the program crashes. If you check the application log you'll see an error including the text from the FailFast call's argument. Also try running within the Visual Studio debugger by pressing F5. When the call to FailFast is encountered the program will stop and display a FatalExecutionEngineError. This allows you to see where the failure happened. No further code will execute.

9 June 2013