liveBook · Manning

ArithmeticException

As explained in Clojure: The Essential Reference

ArithmeticException is a Java runtime exception thrown for invalid arithmetic operations, such as integer division by zero.

ArithmeticException signals an invalid numeric operation in Clojure, commonly integer division by zero, long overflow, or a non-terminating decimal expansion. section 5.5

Watch for these failure cases:

  • Dividing by zero with / throws an ArithmeticException. section 5.5
  • Adding, subtracting, or multiplying long values beyond Long/MAX_VALUE or below Long/MIN_VALUE throws for integer overflow. section 5.5
  • Some BigDecimal divisions produce a non-terminating decimal expansion and require attention to precision. section 5.5

Overflow during lazy computation

(take 7 (iterate #(* % %) 2)) ;; ArithmeticException integer overflow (take 7 (iterate #(*' % %) 2)) ;; (2 4 16 256 65536 4294967296 18446744073709551616N)

How Clojure: The Essential Reference covers it

How deep it goes
Explains division-by-zero, fixed-width overflow, and precision-related cases, but does not detail exception handling syntax.
Examples
Uses overflowing repeated multiplication and contrasts ordinary multiplication with the arbitrary-precision *' operator.
What it assumes
Assumes familiarity with Clojure arithmetic operators and numeric types.
What you can do after
Diagnose arithmetic failures and choose arbitrary-precision multiplication when fixed-width integer overflow is possible.
How it connects
Connects arithmetic operators with integer overflow, division by zero, BigDecimal, arbitrary-precision integers, and numeric types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.