C# 6 Exception Filters Will Improve Your Home Life

If you’re like me and you enjoy nice, peaceful weekends, but keep getting hassled when something bad happens in production to shatter the blissful silence you’re enjoying, a great new feature of C# 6 will help you out:

try {
  // Do stuff
} catch (Exception e) when (
  (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
  || (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) {
  // Swallow
}

Swallow exceptions – but only on weekends! Now you won’t get bothered any more, the app will always be up and running! The error logs will be nice and clean as if nothing has gone wrong at all.

This can be extended if it’s just one person hassling you a lot:

try {
  // Do stuff
} catch (Exception e) when (Thread.CurrentPrincipal.Identity.Name == "JBOGARD") {
  // Swallow
}

The possibilities are endless.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in C#. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • some dude

    Is it possible to be chained?

    catch (Exception e) when () {
    } when() {
    }

    • Is that to apply multiple conditions? If so, would be equivalent to “when (condition1 && condition2)”

      • ishaih

        it could be equivlanet to “when (condition1 || condition2)” (not &&) but if you want to do different things for each case even that isn’t the same solution as multiple when statements

        • In that case you’d use || and then inside the catch block you’d test again to decide what to do.

      • some dude

        yup just like ishaih said, it is for seperate condition,

        try {

        // Do stuff

        } catch (Exception e) when (Thread.CurrentPrincipal.Identity.Name == “JBOGARD”) {

        // Swallow

        }

        when (

        (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)

        || (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) {

        // Swallow

        }

  • Can you reference the exception in the when clause?

    • Absolutely, that would the typical (non-joke!) use of this feature, to filter exceptions in more flexible ways. Previously the only form of filtering was by type, “white-listing”.

  • You don’t need C#6 for that. I had that way back:
    try{
    // do blah
    }catch(Exception){
    // do nothing, don’t care even if not a weekend -)
    }

    • LOL, I really like where your head is at mate. I’m going to start doing the same :-)

    • Joshua Austill

      This made my day :) bwahahaha

  • Matt Burnside

    Nice! One of the very, very, very few features that I have envied in VB.NET.

  • balazs hideghety

    Nice start for a day, with laughing. Thanx!

  • bradykelly

    Great approach to sharing this! Haha.