中級 › ArithmeticException: / by zero の原因と直し方 › パターン3
ArithmeticException: / by zero の原因と直し方
int型同士の割り算・剰余算で分母が0だと例外になります。
1 public class Main { 2 public static void main(String[] args) { 3 int score = 10; 4 ______ denom = 0; ^ 5 try { 6 System.out.println(score / denom); 7 } catch (ArithmeticException e) { 8 System.out.println("caught"); 9 } 10 } 11 }
出力: Infinity期待: caught (コンパイルは通っています)
空欄を埋めてビルドを通す
分母がdouble型だと0除算は例外にならずInfinityになるため、catchブロックが実行されません。
次の問題