Code Fix

上級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

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

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

SwitchExpressionException の原因と直し方

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

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

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