今回のテーマ
今回はC#でよく発生するエラーについてみていきましょう!
エラーによっては、エラーが発生する例と対処方法のソースコードを載せていきますので、
ぜひ最後までみてくださいね!
今回、紹介するエラーは下記となります。
C#でよく発生するエラーとその対処方法
- NullReferenceException
- IndexOutOfRangeException
- InvalidCastException
- DivideByZeroException
- ArgumentException
- FileNotFoundException
- StackOverflowException
- OutOfMemoryException
- FormatException
- InvalidOperationException
KindleUnlimited会員であれば、全ての本をご覧頂けます。 Linqを理解すれば、C#プログラミングの世界が変わる 第1版
-188x300.jpg)
1. NullReferenceException
NullReferenceExceptionは、null参照を呼び出そうとしたときに発生します。
対処方法はnullチェックを行うことです。

1 2 3 4 5 6 7 8 9 10 |
using System; class Program { static void Main() { string s = null; Console.WriteLine(s.Length); } } |
出力結果
NullReferenceException: Object reference not set to an instance of an object.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; class Program { static void Main() { string s = null; if (s != null) { Console.WriteLine(s.Length); } else { Console.WriteLine("s is null"); } } } |
出力結果
s is null

-
-
他の事例と対処方法も見たい方はこちら【C# sharp】NullReferenceExceptionの5つの発生原因と対処方法
ChatGPTのAPIを使わずに自動化することが可能です。 下記の本を読めば、ChatGPT4でも料金掛からずに自動化できます!KindleUnlimited会員であれば無料で読めます。 NullRe ...
続きを見る
2. IndexOutOfRangeException
IndexOutOfRangeExceptionは、配列の範囲外のインデックスにアクセスしようとしたときに発生します。
配列の長さを確認し、範囲内に収まるようにすることが対処方法です。

1 2 3 4 5 6 7 8 9 10 |
using System; class Program { static void Main() { int[] arr = new int[5]; Console.WriteLine(arr[5]); } } |
出力結果
IndexOutOfRangeException: Index was outside the bounds of the array.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; class Program { static void Main() { int[] arr = new int[5]; if (arr.Length > 5) { Console.WriteLine(arr[5]); } else { Console.WriteLine("Index out of range"); } } } |
出力結果
Index out of range

-
-
他の事例と対処方法も見たい方はこちら【C# sharp】IndexOutOfRangeExceptionの5つの発生原因と対処方法
ChatGPTのAPIを使わずに自動化することが可能です。 下記の本を読めば、ChatGPT4でも料金掛からずに自動化できます!KindleUnlimited会員であれば無料で読めます。 C#のInd ...
続きを見る
3. InvalidCastException
InvalidCastExceptionは、互換性のない型へのキャストを試みたときに発生します。
対処方法はキャスト前に型チェックを行うことです。

1 2 3 4 5 6 7 8 9 10 |
using System; class Program { static void Main() { object o = "Hello, World!"; int i = (int)o; } } |
出力結果
InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; class Program { static void Main() { object o = "Hello, World!"; if (o is int i) { Console.WriteLine(i); } else { Console.WriteLine("Cannot cast to int"); } } } |
出力結果
Cannot cast to int

-
-
他の事例と対処方法も見たい方はこちら【C# sharp】InvalidCastExceptionの5つの発生原因と対処方法
ChatGPTのAPIを使わずに自動化することが可能です。 下記の本を読めば、ChatGPT4でも料金掛からずに自動化できます!KindleUnlimited会員であれば無料で読めます。 C#でのIn ...
続きを見る
4. DivideByZeroException
DivideByZeroExceptionは、0で除算を試みたときに発生します。
対処方法は除数が0でないことを確認することです。

1 2 3 4 5 6 7 8 9 10 11 |
using System; class Program { static void Main() { int num = 10; int den = 0; Console.WriteLine(num / den); } } |
出力結果
DivideByZeroException: Attempted to divide by zero.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; class Program { static void Main() { int num = 10; int den = 0; if (den != 0) { Console.WriteLine(num / den); } else { Console.WriteLine("Cannot divide by zero"); } } } |
出力結果
Cannot divide by zero

5. ArgumentException
ArgumentExceptionは、不適切な引数がメソッドに渡されたときに発生します。
対処方法は引数の値を事前にチェックすることです。

1 2 3 4 5 6 7 8 9 10 |
using System; class Program { static void Main() { string s = null; Console.WriteLine(s.Length); } } |
出力結果
ArgumentNullException: Value cannot be null.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; class Program { static void Main() { string s = null; if (s != null) { Console.WriteLine(s.Length); } else { Console.WriteLine("String is null"); } } } |
出力結果
String is null

-
-
他の事例と対処方法も見たい方はこちら【C# sharp】ArgumentExceptionの5つの発生原因と対処方法
ChatGPTのAPIを使わずに自動化することが可能です。 下記の本を読めば、ChatGPT4でも料金掛からずに自動化できます!KindleUnlimited会員であれば無料で読めます。 Argume ...
続きを見る
6. FileNotFoundException
FileNotFoundExceptionは、指定したファイルが見つからないときに発生します。
対処方法はファイルが存在するか確認することです。

1 2 3 4 5 6 7 8 9 10 |
using System; using System.IO; class Program { static void Main() { StreamReader sr = new StreamReader("non_existent_file.txt"); } } |
出力結果
FileNotFoundException: Could not find file 'non_existent_file.txt'.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.IO; class Program { static void Main() { if (File.Exists("non_existent_file.txt")) { StreamReader sr = new StreamReader("non_existent_file.txt"); } else { Console.WriteLine("File does not exist"); } } } |
出力結果
File does not exist

7. StackOverflowException
StackOverflowExceptionは、スタックオーバーフローが発生したとき、つまり再帰的な呼び出しが深すぎるときに発生します。
対処方法は再帰の深さを制限することです。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; class Program { static void Main() { Recursive(1); } static void Recursive(int value) { Console.WriteLine(value); Recursive(value + 1); } } |
出力結果
StackOverflowException

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; class Program { static void Main() { Recursive(1, 10); } static void Recursive(int value, int limit) { if (value <= limit) { Console.WriteLine(value); Recursive(value + 1, limit); } } } |
出力結果
1 2 3 4 5 6 7 8 9 10

8. OutOfMemoryException
OutOfMemoryExceptionは、利用可能なメモリが不足しているときに発生します。
対処方法はメモリの使用量を減らす、または不要なオブジェクトを適切に破棄することです。


9. FormatException
FormatExceptionは、データのフォーマットが無効なときに発生します。
対処方法は入力データのフォーマットを確認し、適切な形式であることを確認することです。

1 2 3 4 5 6 7 8 9 10 |
using System; class Program { static void Main() { string str = "not a number"; int num = int.Parse(str); } } |
出力結果
FormatException

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; class Program { static void Main() { string str = "not a number"; int num; if (int.TryParse(str, out num)) { Console.WriteLine(num); } else { Console.WriteLine("Invalid format"); } } } |
出力結果
Invalid format

-
-
他の事例と対処方法も見たい方はこちら【C# sharp】FormatExceptionの5つの発生原因と対処方法
ChatGPTのAPIを使わずに自動化することが可能です。 下記の本を読めば、ChatGPT4でも料金掛からずに自動化できます!KindleUnlimited会員であれば無料で読めます。 C#における ...
続きを見る
10. InvalidOperationException
InvalidOperationExceptionは、メソッドの呼び出しが無効な状態で行われたときに発生します。
対処方法はメソッドの呼び出しの前にオブジェクトの状態を確認することです。

1 2 3 4 5 6 7 8 9 10 11 |
using System; using System.Collections.Generic; class Program { static void Main() { List list = new List(); list.Remove("test"); } } |
出力結果
InvalidOperationException

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; class Program { static void Main() { List list = new List(); if (list.Contains("test")) { list.Remove("test"); } } } |
出力結果
(無出力)

まとめ
以上、C#でよく見かける10種類のエラーとその対処法を見てきました。
プログラミングはエラーとの戦いの連続ですが、しっかりとエラーメッセージを読み、原因と対処法を理解することで、スキルアップに繋がります。
エラーが発生したら、まずは落ち着いてエラーメッセージを読むことから始めてみてください。
最後まで読んで頂き、ありがとうございました。少しでもお役にたてたなら幸いです!
