Why is "Infinity" generated for #{1/0} in EL with JSF?

Karl Richter :

I needed a page to throw an exception for an experiment and added

#{1/0}

to index.xhtml. I expected an java.lang.ArithmeticException to be thrown, however the expression evaluated to the string Infinity on the generated page. Division by zero is not defined and NaN is probably a much better choice than Infinity, but even NaN is confusing because it's not intuitive in the Java programming language where division by zero is handled with an exception instead of this return value.

Running

@PostConstruct
public void init() {
    int x = 1/0;
}

in a backing bean causes the expected java.lang.ArithmeticException: / by zero.

Besides an explanation why this happens, I'd be interested in a way to throw the exception because I prefer early and severe crashs of the application during development over displaying of logical (or unlogical for that reason) string.

I checked the large list of potential duplicates (x/0 == NaN in other languages, etc.) carefully, but there seems to be no explanation for JSF, yet. I'm not looking for a solution of any kind (there's no problem, I just found this behavior by accident), but an explanation.

I experienced this using Primefaces 6.2.

Stephen C :

This is explained by the specification for Expression Language 3.0, Section 1.7.1:

"Binary operator - A {/,div} B

  • If A and B are null, return (Long)0
  • If A or B is a BigDecimal or a BigInteger, coerce both to BigDecimal and return A.divide(B, BigDecimal.ROUND_HALF_UP)
  • Otherwise, coerce both A and B to Double and apply operator
  • If operator results in exception, error."

In this case, A and B are integers, so they are coerced to Double and the division is performed using IEE 754 floating point arithmetic ... resulting in an INF.

There's probably no way to thrown an exception, then.

There are ways:

  • If A or B (but not both) are null, then the spec implies you would get an NPE.
  • In the BigInteger and BigDecimal cases, the divide method should throw an ArithmeticException if B is zero.

Reference:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=82191&siteId=1