A Fluent Way of Exception Handling

While doing some filesystem work I encountered alot of AccessViolationExceptions because a file is being opened to write multiple times.  Even after closing the file explicitly a short timeframe exists in which the file could not be opened again.  The simplest approach for me was to retry openening the file until it worked.  To allow a more easy and more general way to handle exceptions I developed a small extensible try-repeat-framework which allows me to configure waiting and repeating strategies and also to only react to specific exceptions.  I have written it with a fluent interface which allows easy usage:

New: I created a Repository on Github : https://github.com/toeb/fluentexceptions Even newer: you can now install it via nuget:  PM> Install-Package Core.Trying

Example 1:

var configuration = new Try()
        // do not throw exceptions 
        // when action continouosly fails
        // only expectAccessViolationExceptions
        // repeat at most 5 times or until 
        // 1s of waiting time has passed
      .Repeat(5, 1000)
        // when actions fails backoff exponentially
        // e.g. first wait 10 ms then 100 ms then 1000ms
      //configuration is reusable
      var result = configuration.Execute(() =>
        /*something which potentially throws */

      if (result)
        // success
        Console.Write("number of retries: ");
        // failure
        Console.Write("time spent waiting [ms]: ");
        Console.Write("number of retries: ");
        Console.Write("last throw exception message: ");

Example 2:

// default configuration handles any exception
  // repeats 4 times at most and exponentially backs off
  Try.Default.Execute(() => {
    /*some action which potentially throws*/

let me know if you think it is useful…  Be warned that this type of repeat on exception strategy should not be applied blindly …

I developed the library because I needed it but some terminology was researched.  consulted sources:

4 comments for “A Fluent Way of Exception Handling

  1. 2013/12/09 at 21:04

    Why don’t you put it up on Github?

    • 2013/12/09 at 22:44

      Its part of another project, I haven’t had the time to create a repo. But I probably will soon

  2. 2013/12/09 at 23:04

    Btw, that is very similar to Transient Fault Handling in Microsoft Enterprise Library: http://msdn.microsoft.com/en-us/library/hh680905(v=pandp.50).aspx

    • 2013/12/10 at 00:56

      yeah i noticed. after starting to write this little library i also came across the transient fault handling lib (while i was researching how it would be called to delay after a fault – i used their term “backoff”) I should probably get into the habit of posting sources and inspiration

Leave a Reply

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