rksoftware

Visual Studio とか C# とかが好きです

C# 2.0 以降の新機能の確認 - C# 6.0 - 例外をフィルター処理する述語式 (when)

C# 2.0 以降の新機能を一つづつ確認していきます。
以前に一度行ったのですが、公式ドキュメント再編でリンク切れしているところを見つけてしまったので。今ならもっと簡潔なサンプルが欠けるところもあるだろうし、せっかくなので今もう一度確認して行きます。

例外をフィルター処理する述語式 (when)

 https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/keywords/try-catch
 処理対象の例外をフィルターする際に、例外オブジェクトの型の評価に続いて、述語式を使用して例外をフィルターできる。

static void Main(string[] args)
{
    MethodA(null, "text");  // text1:Null または Empty です (Parameter 'text1')
    MethodA("text", null);  // text1:Null または Empty です (Parameter 'text2')
}
static void MethodA(string text1, string text2)
{
    try
    {
        MethodB(text1, text2);
    }
    // 例外の型のみでなくプロパティの内容も評価してフィルター ex.ParamName == "text1" の場合のみ
    catch (ArgumentException ex) when (ex.ParamName == "text1")
    {
        Console.WriteLine($"{nameof(text1)}:{ex.Message}");
    }
    // 例外の型のみでなくプロパティの内容も評価してフィルター ex.ParamName == "text2" の場合のみ
    catch (ArgumentException ex) when (ex.ParamName == "text2")
    {
        Console.WriteLine($"{nameof(text2)}:{ex.Message}");
    }
}

static void MethodB(string text1, string text2)
{
    if (string.IsNullOrEmpty(text1)) throw new ArgumentException("Null または Empty です", nameof(text1));
    if (string.IsNullOrEmpty(text2)) throw new ArgumentException("Null または Empty です", nameof(text2));
}