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 にします。
パターン4
1 class Program { 2 static void Main(string[] args) { 3 int budget = 500; 4 int teams = 0 ; ^ 5 System.Console.WriteLine(budget / teams); 6 } 7 }
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at Program.Main(String[] args) in Program.cs:line 5
整数の0除算はDivideByZeroExceptionになります。
直し方: 0 を 5 にします。
パターン5
1 class Program { 2 static void Main(string[] args) { 3 int stock = 40; 4 int boxes = 5 - 5; ^ 5 System.Console.WriteLine(stock / boxes); 6 } 7 }
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at Program.Main(String[] args) in Program.cs:line 5
5 - 5は0になるため、boxesが0のまま除算が実行され例外になります。
直し方: - を + にします。
よくある誤解
整数の0除算は例外になりますが、double型の0除算は例外にならずInfinityやNaNを返します。型によって挙動が違う点に注意してください。
実務での勘所
整数の0除算は、後述するchecked/uncheckedのオーバーフロー検出設定とは無関係に、常に例外(DivideByZeroException)になります。checkedコンテキストを指定しなければ黙って折り返るオーバーフローとは違い、0除算はC#の既定の挙動として常に検出される、という点は区別して覚える必要があります。「整数がらみの計算で危険なことが起きる」という点は共通していても、検出されるかどうかの扱いは別々に決まっています。