Math.sqrt(-5)->在JSP中强制异常? [英] Math.sqrt(-5) -> Force Exception in JSP?

查看:106
本文介绍了Math.sqrt(-5)->在JSP中强制异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个.jsp文件. index.jsp和sqrtcalculator.jsp和error.jsp.

I've 3 .jsp files. index.jsp and sqrtcalculator.jsp and error.jsp.

在index.jsp中,有一个文本字段和一个按钮.在sqrtcalculator.jps中,有一个计算器.

In index.jsp there's a text field and a button. In sqrtcalculator.jps there's the, well, calculator.

现在,当我将该字段留空并按下按钮时,就会调用一个期望值,因为该字段为空.然后,我可以重新路由到单个error.jsp站点以显示错误和异常堆栈,如

Now, when I leave the field empty and press the button, an expection is called, because the field is empty. And I can then reroute to an individual error.jsp site to display the errors, and exception stack like

<%= request.getAttribute("javax.servlet.error.request_uri") %>
<%= exception.getMessage() %>
<%= exception %>

问题是,当我在文本字段中输入-5时,我无法获得异常,因为Math.sqrt(-5)不会返回错误,而是"NaN".

Problem is, when I enter -5 in the textfield, I can't get an exception, because Math.sqrt(-5) doesn't return an error but "NaN".

如何强制将其作为例外?想法是将用户重新路由到单独的error.jsp并显示错误.但是就像我说过Math.sqrt(-5)不会返回错误或异常,而是返回"NaN"文本字符串.

How can I force it to be an exception? The idea is to reroute the user to an individual error.jsp and displaying the errors. But like I said Math.sqrt(-5) doesn't return errors or exceptions but "NaN" textstring.

我不想要这样的东西,仅供参考

I don't want something like this just FYI

<%if (NaN){
%>
<p>Nope, Square root from negative numbers is not defined!</p>
<%}
%>

推荐答案

警告,先前答案中对NaN的测试是错误的(NaN不等于自身).在Java中,测试NaN的更好方法是

Warning, the test for NaN in the previous answer is wrong (NaN is NOT equal to itself). In Java the better way to test for NaN is

if (Double.isNaN(answer)) {
  // throw exception
}

或者

if (answer != answer) {
}

虽然第二个版本可以使用,但一定会让那些不了解NaN奇怪行为的人感到困惑.

While this second version will work, it is sure to puzzle those not aware of the curious behaviour of NaN.

这篇关于Math.sqrt(-5)-&gt;在JSP中强制异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆