๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Exception Filters

An exception filter adds a condition to a catch block. The block runs only when the exception type matches and the condition is true.

A filter that matches

The thrown message names code 404. The filter tests for that exact message and catches it.

using System;

class Program
{
    static void CheckStatus(int code)
    {
        if (code != 200)
        {
            throw new InvalidOperationException("Code " + code);
        }
        Console.WriteLine("Status OK");
    }

    static void Main(string[] args)
    {
        try
        {
            CheckStatus(404);
        }
        catch (InvalidOperationException ex) when (ex.Message == "Code 404")
        {
            Console.WriteLine("Not found handled");
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Other error: " + ex.Message);
        }
    }
}

A filter that turns away

Code 500 fails the filter test. The exception falls through to the plain catch below.

using System;

class Program
{
    static void CheckStatus(int code)
    {
        if (code != 200)
        {
            throw new InvalidOperationException("Code " + code);
        }
        Console.WriteLine("Status OK");
    }

    static void Main(string[] args)
    {
        try
        {
            CheckStatus(500);
        }
        catch (InvalidOperationException ex) when (ex.Message == "Code 404")
        {
            Console.WriteLine("Not found handled");
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Other error: " + ex.Message);
        }
    }
}

Filter on a code value

This filter tests a variable from the surrounding code. A code of 500 or more counts as a server problem.

using System;

class Program
{
    static void CheckStatus(int code)
    {
        if (code != 200)
        {
            throw new InvalidOperationException("Code " + code);
        }
        Console.WriteLine("Status OK");
    }

    static void Main(string[] args)
    {
        int code = 503;
        try
        {
            CheckStatus(code);
        }
        catch (InvalidOperationException ex) when (code >= 500)
        {
            Console.WriteLine("Server problem: " + ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Other error: " + ex.Message);
        }
    }
}

Example

using System;

class Program
{
    static void PlaceOrder(int items)
    {
        if (items <= 0)
        {
            throw new InvalidOperationException("Items " + items);
        }
        Console.WriteLine("Order placed");
    }

    static void Main(string[] args)
    {
        try
        {
            PlaceOrder(0);
        }
        catch (InvalidOperationException ex) when (ex.Message == "Items 0")
        {
            Console.WriteLine("Empty order skipped");
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Order error: " + ex.Message);
        }
    }
}

Key points

  • A filter starts with the word when after the catch part.
  • The condition sits in brackets after when.
  • A true condition lets the catch block run.
  • A false condition sends the exception to the next catch block.
  • Catch blocks are tried in order from top to bottom.
  • A filter can test the message of the exception.
  • A filter can also test a value from the code around it.

In this example, PlaceOrder throws because the order holds no items. The filter matches the message for zero items. The first catch block prints its own line, and the plain catch below never runs.

Note

A plain catch after a filtered catch catches what the filter turns away.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does a filtered catch block run?