js| page In this article, I'll explain how a JSP page exception (exceptions) is thrown (Throw) and how to catch these exceptions so that you can get better information in your JSP design.
First of all, what is exceptions? It is well known that exceptions is an exceptional event that may appear anywhere in the program, for example: You are trying to connect to a database, but the database is closed, and an exception is generated.
How do I catch (throw) an exception? We can use the following expression:
<%
try {
Code which can throw can exception
catch (Exception e) {
Exception Handler code here
}
%>
There is, of course, another useful way: To specify a dedicated exception-handling page that is handled when an exception occurs. That's what I'm going to tell you.
Create three pages: 1.form.html (simple age input basket) code is as follows:
Age = Integer.parseint (Request.getparameter (' age '));
%>
<%--displaying User age--%>
<p>your age are: <%= age%> years.</p>
<p><a href= "form.html" >Back</a>.</p>
</body>
Please note: (1) <%@ page errorpage= "exceptionhandler.jsp"%> is an exception-handling page that must be in the first line of the JSP. (2)
<%
int age;
Age = Integer.parseint (Request.getparameter (' age '));
The%> is to get the age (String Class) and convert to int (class). <p>your age is: <%= age%> years.</p> is the age that you just entered, and now the exception may occur if You're not typing a number, like: Zsa; Can a string be converted to int? 3.exceptionhandler.jsp (Process exception) code is as follows: <%@ page iserrorpage= "true" import= "java.io. * "%>
<title>exceptional even occurred!</title>
<style>
Body, p {font-family:tahoma; font-size:10pt; padding-left:30;}
Pre {font-size:8pt;}
</style>
<body>
</body>
StringWriter SW = new StringWriter ();
PrintWriter pw = new PrintWriter (SW);
Exception.printstacktrace (PW);
Out.print (SW);
Sw.close ();
Pw.close ();
Out.println ("-->");
%> used the PrintWriter and Stringwrighter classes, so you have to declare: import java.io.* in your JSP program, namely: <%@ page iserrorpage= "true" import= " Java.io.* "%> Good: Start Demo: In IE input http://localhost:8080/myapp/Form.html enter!" Of course, you start tomcat! first. You see that? Enter any number in the input basket: 24 etc: The result is: Your age is:24 years try again: input: Zsa. What's the result? Java.lang.NumberFormatException:For input string: "Zsa"; you got it!!!!
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.