CHS
CHS

Reputation: 183

java.lang.ArithmeticException: Division is undefined

I have a simple operation going on in my program:

exposureNoDecimals =
    BigDecimal.valueOf(curEffSpreadPremium).multiply(BigDecimal.valueOf(100)).divide(wsRate, 0,
        java.math.RoundingMode.HALF_UP).longValue();

exposureNoDecimals - long curEffSpreadPremium - long wsRate - BigDecimal

However I am getting

"java.lang.ArithmeticException: Division is undefined" 
  at java.math.BigDecimal.longScaledDivide(BigDecimal.java:3105)
  at java.math.BigDecimal.divide(BigDecimal.java:2409)
  at java.math.BigDecimal.divide(BigDecimal.java:2396)
  at java.math.BigDecimal.divide(BigDecimal.java:2361)

The problem is the issue is recreatable on production and not on my machine (cant debug, or cant see the inputs)

What can be the issue here? Any suggestions/ideas?

Upvotes: 15

Views: 29512

Answers (2)

Stephen C
Stephen C

Reputation: 718926

Take a look at the source code for BigDecimal (e.g. here).

An ArithmeticException is only thrown with the message "Division undefined" when you attempt to divide zero by zero.

I'm not going to suggest a fix, because the >>correct<< fix will depend on what this calculation is supposed to be doing, and why the divisor / dividend happen to be zero. Putting in some zero checks might be a solution, but it could also be a "band-aid solution" that hides the problem rather than fixing it. It could come back to bite you later on.


The problem is the issue is recreatable on production and not on my machine (cant debug, or cant see the inputs)

As noted in various comments, there are different versions of BigDecimal depending on the Java version and (apparently) vendor. One of the differences between (some) versions is that the exception messages differ.

If you really want to track this down this reproducibility issue, you are going to have to look at the source code for BigDecimal in production and on your machine. (Unfortunately, a stacktrace involving Java SE classes is often difficult to diagnose without precise Java vendor and version number information. It is not helpful in this case ... for that reason.)

Upvotes: 25

Hendrik
Hendrik

Reputation: 5310

According to the source code of BigDecimal, java.lang.ArithmeticException: Division undefined (without the is) is only thrown when you divide zero by zero.

Looks like in your case curEffSpreadPremium and wsRate both are zero.

So you need to guard the line with zero-checks.

Upvotes: 1

Related Questions