Environment.FailFast

How FailFast can be used to skip the finally block

Home DailyDrop

Daily Knowledge Drop

The Environment.FaiFast method can be used to close an application without calling any finally blocks or finalizers.


FailFast sample

In the below simple example, the application will try save a record to the database:

  • if a non-connectivity related exception occurs, the error message is saved to the database. On exit of the code block (in the finally), a information message is also logged to the database
  • if a connectivity related exception occurs, the system is obviously unable to save the exception to the database. So instead the application will call the FailFast method to close the application and bypass any database logging in the finally block.
try
{
    SaveRecordToDatabase();
}
catch(Exception ex)
{
    if(ex.Message == "Database connection exception")
    {
        Environment.FailFast(ex.Message);
    }

    LogExceptionToDatabase(ex);
}
finally
{
    LogMessageToDatabase();
}

Success output

When the record is saved without an exception, the output would be as follows:

SaveRecordToDatabase => Record saved successfully
LogMessageToDatabase => Finished processing record

Non-connectivity error

When the record is saved with a non-connectivity exception, the output would be as follows:

LogExceptionToDatabase => PK violation exception
LogMessageToDatabase => Finished processing records

From the output, one can see the LogMessageToDatabase method in the finally block is called.


Connectivity error

When the record is saved with a connectivity exception, the output would be as follows:

Process terminated. Database connection exception
   at System.Environment.FailFast(System.String)
   at Program.<Main>$(System.String[])

In this case, after the FailFast method is called, the application process is terminated without the finally block being called.


Notes

A fairly niche use case, but useful to know it possible to bypass any finally blocks or finalizers (deconstructor) if the need is there. The other alternative is to put checks in the finally and finalizers to exclude there execution in certain cases - but this "pollutes" the code unnecessarily.


References

12. Environment.FailFast()

Daily Drop 66: 04-05-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net failfast finally