Attempted to divide by zero の原因と直し方
整数の除算・剰余演算で除数が0のときに発生します。浮動小数点数の0除算とは挙動が異なる点に注意が必要です。
エラーメッセージの読み方
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
System- 名前空間 — System なら標準の基本例外です
DivideByZeroException- 例外クラス — 何が起きたか。ここを検索するのが最短です
Attempted to divide by zero.- 詳細メッセージ — どの値が問題だったか
at Program.Main(String[] args) in Program.cs:line 5- 発生箇所 — スタックトレースの先頭行
このエラーが出る典型パターン
パターン1
1 class Program { 2 static void Main(string[] args) { 3 int a = 10; 4 int b = 0; ^ 5 System.Console.WriteLine(a / b); 6 } 7 }
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at Program.Main(String[] args) in Program.cs:line 5
整数の0除算は例外になります。浮動小数点数の0除算(Infinity)とは扱いが異なります。
直し方: 0 を 2 にします。
広告
広告スロット(未設定)
パターン2
1 class Program { 2 static void Main(string[] args) { 3 int a = 10; 4 int b = 0 ; ^ 5 System.Console.WriteLine(a % b); 6 } 7 }
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at Program.Main(String[] args) in Program.cs:line 5
剰余演算子%も内部的には除算を行うため、0で割ろうとすると同じ例外になります。
直し方: 0 を 3 にします。
パターン3
1 class Program { 2 static void Main(string[] args) { 3 int total = 100; 4 int count = 0 ; ^ 5 System.Console.WriteLine(total / count); 6 } 7 }
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at Program.Main(String[] args) in Program.cs:line 5
件数が0のときに合計を割ってしまう典型的なパターンです。平均計算などで起きがちです。
直し方: 0 を 4 にします。
よくある誤解
整数の0除算は例外になりますが、double型の0除算は例外にならずInfinityやNaNを返します。型によって挙動が違う点に注意してください。
まとめ
Attempted to divide by zeroは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。