C# exception filter?

前端 未结 4 1869
北恋
北恋 2020-12-10 04:04

Does C# support compiling filters? How do filters even work or what do they do?

Like reflector decompiles a filter as

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


        
4条回答
  •  死守一世寂寞
    2020-12-10 04:30

    While catching exceptions, if you want to handle the exceptions differently then you can use Exception Filter
    -- After C# 6.0
    -- After VB 7.1 Using WHEN

    1) C# Sample After C# 6.0

    try
    {
        throw new CustomException { Severity = 100 };
    }
    catch (CustomException ex) when (ex.Severity > 50)
    {
        Console.WriteLine("*BING BING* WARNING *BING BING*");
    }
    catch (CustomException ex)
    {
        Console.WriteLine("Whooops!");
    }
    

    Note : Keep in mind that the order matters

    2) C# Sample Before C# 6.0

    try
    {
        throw new CustomException { Severity = 100 };
    }
    catch (CustomException ex)
    {
       if (ex.Severity > 50)
        {
           Console.WriteLine("*BING BING* WARNING *BING BING*");
        }
       else
        {
           Console.WriteLine("Whooops!");
        }
    }
    

    Since this piece of code is equivalent to the previous one. means, they are equivalent, right? --- "But No they are not equivalent"
    NOTE : exception filters don’t unwind the stack

    Read it more from Here

提交回复
热议问题