javascript - jsp为什么catch里面的代码不执行?
PHP中文网
PHP中文网 2017-04-11 11:27:49
0
2
231

User.java

public class User { public User(){ } public static void checkUser(String username,String password) throws UsernameException{ try{ Connection connection = ConnectionUtils.getConnection(); String sql = "select * from user where username="+username; Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql); if(!result.next()){ throw new UsernameException("用户名异常"); } }catch(Exception e){ e.printStackTrace(); } } }

login.jsp

<% response.setCharacterEncoding("utf-8"); String action = request.getParameter("action"); String username = request.getParameter("username"); String password = request.getParameter("password"); if(action != null && action.equals("login")){ try{ User.checkUser(username, password); }catch(UsernameException e){ out.println("该用户名不存在!"); return; } out.println("ddddd"); } %>

为什么out.println("该用户名不存在!");没打印到页面上?

而下面的代码改了处理异常的就可以打印了

User.java

public class User { public User(){ } public static void checkUser(String username,String password) throws Exception, UsernameException{ Connection connection = ConnectionUtils.getConnection(); String sql = "select * from user where username="+username; Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql); try{ if(!result.next()){ throw new UsernameException("用户名异常"); } }catch(SQLException e){ e.printStackTrace(); } } }

改为SQLException 就可以了 。。这里为什么要用SQLException ?
刚接触到java的异常处理。。不是很懂,求大神指点。。Thanks

PHP中文网
PHP中文网

认证0级讲师

reply all (2)
大家讲道理

因为在User.java中你已经把UsernameException给捕获了

    Ty80

    因为在checkUser这个方法中你try catch了Exception,这个就处理了所有的异常(包括UsernameException),因为其他的异常都是继承他的,所以都会捕获。你需要把checkUser方法中catch的内容改变。或者在catch之后判断异常是否为UsernameException再抛出来。

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!