![]() 在这篇文章中,我将向您讲解一个jsp页面例外(Exceptions)是怎样抛出(Throw)并且怎样捕获这些例外,以便使您在jsp设计中能得到更有利的信息. 首先,什么是Exceptions?众所周知Exceptions就是个异常事件,他可能出现在程式的任何地方,比如:您试图连接一个数据库,但是这个数据库已关闭,这时就产生一个例外. 怎样捕获(throw)一个例外啦?我们能够用下面的表达式: <% try { // Code which can throw can exception } catch(Exception e) { // Exception handler code here } %> 当然,更有另外的一种有用的方法:就是指定专用的例外处理页面,当例外发生时便由他来处理.这就是我下面要讲述的. 建立三个页面:1.Form.html(简单的年龄输入筐)代码如下: 2:FormHandler.jsp()(处理由Form.html传来的age)代码如下: <%@ page errorPage="ExceptionHandler.jsp" %> <%-- Form Handler Code --%> <% int age; age = Integer.parseInt(request.getParameter("age")); %> <%-- Displaying User Age --%> Your age is : <%= age %> years. Back. 请注意:(1)<%@ page errorPage="ExceptionHandler.jsp" %>是指明了一个例外处理页面,他必须在jsp的第一行.(2) <% int age; age = Integer.parseInt(request.getParameter("age")); %>是取得age(String类)并转化为int(类). Your age is : <%= age %> years. 是输出您刚才输入的age,现在例外就可能发生了,假如 您输入的不是数字,比如:zsa;这时String能转化成int吗?3.ExceptionHandler.jsp(处理例外)代码如下:<%@ page isErrorPage="true" import="java.io.*" %><%-- Exception Handler --%> <%= exception.toString() %> <% out.println(""); %> 注意:<%@ page isErrorPage="true" %>表明:当jsp宣称了一个errorPage时,应该声明isErrorPage="true; <% out.println(""); %>运用了PrintWriter和StringWrighter类,所以您不得不声明:import java.io.* 在您jsp程式中;即:<%@ page isErrorPage="true" import="java.io.*" %>好了:开始演示:在ie中输入http://localhost:8080/myapp/Form.html 回车!当然您先要启动tomcat! 看见了吗?在输入筐中入任何一个数字:24等:结果是:Your age is : 24 years再试一下:输入:zsa.是什么结果啦??java.lang.NumberFormatException: For input string: "zsa";明白了吧!!!! |
喜欢本文,那就收藏到: |