上級 › SwitchExpressionException の原因と直し方 › パターン1
SwitchExpressionException の原因と直し方
switch式が全てのパターンを網羅していないとき、コンパイラは警告を出しますが止めません。
1 class Program { 2 static string Describe(int n) { 3 return n switch { 4 1 => "one", 5 2 => "two", 6 }; 7 } 8 static void Main(string[] args) { 9 System.Console.WriteLine(Describe(_)); ^ 10 } 11 }
Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input.
at Program.Describe(Int32 n) in Program.cs:line 3
空欄を埋めてビルドを通す
switch式は網羅していないパターンがあると、そこに来たときだけ実行時に失敗します。コンパイラは警告は出しますが止めてはくれません。
次の問題