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" にします。
パターン4
1 class Program { 2 static void Main(string[] args) { 3 int n = int.Parse("ten"); ^ 4 System.Console.WriteLine(n); 5 } 6 }
Unhandled exception. System.FormatException: The input string 'ten' was not in a correct format.
at Program.Main(String[] args) in Program.cs:line 3
int.Parseは数字だけの文字列しか変換できません。英単語が混じるとFormatExceptionになります。
直し方: "ten" を "10" にします。
パターン5
1 class Program { 2 static void Main(string[] args) { 3 int n = int.Parse("3,000" ); ^ 4 System.Console.WriteLine(n); 5 } 6 }
Unhandled exception. System.FormatException: The input string '3,000' was not in a correct format.
at Program.Main(String[] args) in Program.cs:line 3
桁区切りのカンマもint.Parseは数字として認識できません。
直し方: "3,000" を "3000" にします。
よくある誤解
int.Parseは数字だけの文字列しか受け付けません。空文字列や小数点を含む文字列を渡すと、TryParseと違って例外で失敗を知らせます。
実務での勘所
.NETがParseとTryParseの両方を用意しているのは、失敗が「本当に起こってはいけない異常事態」なのか「起こりうる普通の結果」なのかで使い分けてほしいという設計意図の表れです。これはMicrosoftが公式に文書化している「Try-Parseパターン」というガイドラインで、ユーザー入力のように失敗が当たり前に起こりうる場面ではTryParse(失敗時は例外を投げずfalseを返す)を、値が正しいことが前提として保証されている場面ではParseを使うことが推奨されています。