Java 捕获jsp中的nullpointerexception失败
编写此代码是为了捕获nullpointerexceptionJava 捕获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
<%@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块,随后在使用nullp
时会遇到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>