Exception filters in C#

Excpetions filters is new in C# 6.0. With an exception filter it's now possible to place a filter on the catch statement. This filter has a condition for enter this catch method. If this condition is met the catch body is entered otherwise the catch is passed and keeping the full error trace. Keeping the full error trace can be important and helpful with debugging.

      public class MyProgram
    {
        public void TestFilterMethod()
        {
            try
            {
                DoSomeThingWrong(true);
            }
            catch (MyException ex) when (ex.Code == 42)
            {
                Console.WriteLine("Error 42 occurred");
            }
        }

        private void DoSomeThingWrong(bool wrong)
        {
            if(wrong)
            {
                throw new MyException() { Code = 42 };
            }
        }
    }

    public class MyException: Exception
    {
        public int Code { get; set; }
    }

So in this example only the exception with code 42 is handled the rest is catched at a higher level.

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!