Code Fix

上級SwitchExpressionException の原因と直し方 › パターン3

SwitchExpressionException の原因と直し方

switch式が全てのパターンを網羅していないとき、コンパイラは警告を出しますが止めません。

 1  class Program {
 2      static string Label(int code) {
 3          return code switch {
 4              200 => "OK",
 5              404 => "Not Found",
 6          };
 7      }
 8      static void Main(string[] args) {
 9          System.Console.WriteLine(Label(___));
                                            ^
10      }
11  }
Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input. at Program.Label(Int32 code) in Program.cs:line 3

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

SwitchExpressionException の原因と直し方

網羅されていない値が実際に渡された瞬間に実行時エラーになります。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)