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.
This is explained by the specification for Expression Language 3.0, Section 1.7.1:
"Binary operator -
A
{/,div}B
- If
A
andB
arenull
, return(Long)0
- If
A
orB
is aBigDecimal
or aBigInteger
, coerce both toBigDecimal
and returnA.divide(B, BigDecimal.ROUND_HALF_UP)
- Otherwise, coerce both
A
andB
toDouble
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
orB
(but not both) arenull
, then the spec implies you would get an NPE. - In the
BigInteger
andBigDecimal
cases, thedivide
method should throw anArithmeticException
ifB
is zero.
Reference:
- JSR-000341 Expression Language 3.0 - http://download.oracle.com/otndocs/jcp/el-3_0-fr-eval-spec/index.html