Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 捕获jsp中的nullpointerexception失败_Java_Jsp - Fatal编程技术网

Java 捕获jsp中的nullpointerexception失败

Java 捕获jsp中的nullpointerexception失败,java,jsp,Java,Jsp,编写此代码是为了捕获nullpointerexception <%@page import="model.Personne"%> <% Personne p; try { p = (Personne) request.getAttribute("test"); } catch (NullPointerException e) { out.print("<p>Exception catched " + e.get

编写此代码是为了捕获nullpointerexception

<%@page import="model.Personne"%>
<%
    Personne p;
    try {
        p = (Personne) request.getAttribute("test");
    } catch (NullPointerException e) {
        out.print("<p>Exception catched " + e.getMessage() + "</p>");
        p = new Personne();
        p.name = "Albert";
    }
%>
关于Personne,这是一个非常简单的类,仅用于测试。

p = (Personne) request.getAttribute("test");

抛出一个
NullPointerException
,但如果请求不包含属性
test
,则
p
将仅为null。因此,不会执行catch块,随后在使用null
p
时会遇到
NullPointerException
异常,调用实例方法或属性时会发生null指针异常。行中:

p = (Personne) request.getAttribute("test"); 
唯一的实例是“request”,它永远不会为null

您的逻辑必须是这样的:

Personne p;
p = (Personne) request.getAttribute("test");
if (p == null) {
    p = new Personne();
    p.name = "Albert";
}

试试这个简单的例子,你会发现
NullPointerException
将被捕获:

<%
    try {
        String p = null;
        out.print(p.toString());
    } catch (NullPointerException e) {
        out.print("<p>Exception catched " + e.getMessage() + "</p>");
    }
%>


正如wero所说,我假设NPE稍后抛出。

您可以在jsp页面中使用JSTL核心标记。 这是一个例子

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:catch> Tag Example</title>
</head>
<body>

<c:catch var ="catchException">
<%    Personne p; 
p = (Personne) request.getAttribute("test"); %>
</c:catch>

<c:if test = "${catchException != null}">
   <p>The exception is : ${catchException} <br />
   <%  p = new Personne();
       p.name = "Albert"; %>
</c:if>

</body>
</html>

标签示例
异常为:${catchException}

首先如何防止
null
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:catch> Tag Example</title>
</head>
<body>

<c:catch var ="catchException">
<%    Personne p; 
p = (Personne) request.getAttribute("test"); %>
</c:catch>

<c:if test = "${catchException != null}">
   <p>The exception is : ${catchException} <br />
   <%  p = new Personne();
       p.name = "Albert"; %>
</c:if>

</body>
</html>