如何获得2个或更多不同的例外?

Vin*_* Vm 2 java sql jsp servlets exception-handling

我编写了一个代码来将用户添加到DB中.当我们收到重复的条目时,我需要重定向到EmpInfo.jsp.我需要使用更多的例外,我也想知道如何重定向.

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "cervlet";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root"; 
String password = "1234";
int Empid =Integer.parseInt(request.getParameter("Empid").toString()); 
String Name = request.getParameter("Name").toString();
int Age =Integer.parseInt(request.getParameter("Age").toString()); 
int Salary =Integer.parseInt(request.getParameter("Salary").toString());
PreparedStatement stmt;
try {
 Class.forName(driver).newInstance();
 conn = DriverManager.getConnection(url+dbName,userName,password);
 System.out.println("Connected to the database");
 //ArrayList al=null;
 //ArrayList userList =new ArrayList();
 String query = "insert into employee set Empid='"+Empid+"',name='"+Name+"',Age='"+Age+"',Salary='"+Salary+"'";
stmt = (PreparedStatement) conn.prepareStatement(query);
  int i = 0;
try {
   i = stmt.executeUpdate(query);
    }
  catch (SQLException e) {
    String nextj = "/AddUser.jsp";
    RequestDispatcher rd = getServletContext().getRequestDispatcher(nextj);
   rd.forward(request, response);
    }
   System.out.println("i="+i);
System.out.println("query: " + query);
//if(i==0)
 //{
  //String nextj = "/EmpInfo.jsp";
    //RequestDispatcher cd = getServletContext().getRequestDispatcher(nextj);
    //cd.forward(request, response);
 //response.sendRedirect("servletRecord");
//}
 response.sendRedirect("/EmpInfo.jsp");
 conn.close();
 System.out.println("Disconnected from database");

} catch (Exception e) {
e.printStackTrace();
Run Code Online (Sandbox Code Playgroud)

更新

当我EmpInfo.jsp添加一个新条目时,我需要重定向到.执行该方法后executeUpadte(),我使用其返回值重定向到另一个名为的页面EmpInfo.jsp.但它没有重定向.我正在使用eclipse.告诉我多次重定向.jsp页面的常用方法.

jjn*_*guy 9

好吧,如果你问如何捕获不同的异常,下面的代码是你如何做到的:

try {
    ...
    // Code that may throw a few types of exceptions
    ...
} catch(FileNotFoundException fnfe) {
    // handle very specific exceptions
} catch (IOException ioe) {
    // handle less specific exceptions
} catch (Exception e) {
    // handle the most generic exception case
} 
Run Code Online (Sandbox Code Playgroud)

这将允许您在一个代码块中处理多个异常类型.