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