Code Fix

初級

The input string was not in a correct format の原因と直し方

int.Parseなどの変換メソッドに、数値として解釈できない文字列を渡したときに発生します。

エラーメッセージの読み方

Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.
System
名前空間 — System なら標準の基本例外です
FormatException
例外クラス — 何が起きたか。ここを検索するのが最短です
The input string 'abc' was not in a correct format.
詳細メッセージ — どの値が問題だったか
at Program.Main(String[] args) in Program.cs:line 3
発生箇所 — スタックトレースの先頭行

このエラーが出る典型パターン

パターン1

 1  class Program {
 2      static void Main(string[] args) {
 3          int n = int.Parse("abc");
                                ^
 4          System.Console.WriteLine(n);
 5      }
 6  }
Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format. at Program.Main(String[] args) in Program.cs:line 3

int.Parseは数字だけの文字列しか変換できません。数字以外の文字が混じるとFormatExceptionになります。

直し方: "abc""123" にします。

この問題を解いてみる →

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

パターン2

 1  class Program {
 2      static void Main(string[] args) {
 3          int n = int.Parse("12.5");
                                 ^
 4          System.Console.WriteLine(n);
 5      }
 6  }
Unhandled exception. System.FormatException: The input string '12.5' was not in a correct format. at Program.Main(String[] args) in Program.cs:line 3

int.Parseは小数点を含む文字列を受け付けません。小数はdouble.Parseを使う必要があります。

直し方: "12.5""12" にします。

この問題を解いてみる →

パターン3

 1  class Program {
 2      static void Main(string[] args) {
 3          int n = int.Parse(""  );
                                ^
 4          System.Console.WriteLine(n);
 5      }
 6  }
Unhandled exception. System.FormatException: The input string '' was not in a correct format. at Program.Main(String[] args) in Program.cs:line 3

空文字列は数字を1つも含まないため、int.ParseはFormatExceptionを投げます。

直し方: """7" にします。

この問題を解いてみる →

よくある誤解

int.Parseは数字だけの文字列しか受け付けません。空文字列や小数点を含む文字列を渡すと、TryParseと違って例外で失敗を知らせます。

まとめ

The input string was not in a correct formatは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

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