[英]Java - Exception not being caught
This is the exception I created这是我创建的异常
public class UserNaoExiste extends Exception {
public UserNaoExiste(){
super("User não existe");
}
}
This is the function where the exception is thrown (it is in fact thrown, I believe)这是抛出异常的函数(我相信它实际上是抛出的)
public Entidades.User getUser(String username) throws Exceptions.UserNaoExiste {
Entidades.User u = null;
try (Connection con = DriverManager.getConnection(this.url, this.username, this.password)) {
PreparedStatement stm = con.prepareStatement("SELECT * FROM user WHERE username = ?");
stm.setString(1, username);
ResultSet rs = stm.executeQuery();
if (rs.next() == false) {
throw new Exceptions.UserNaoExiste();
}
u = new Entidades.User(rs.getString("Username"), rs.getString("Password"), rs.getString("Nick"), rs.getString("Admin"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
return u;
}
This is where the exception SHOULD be caught这是应该捕获异常的地方
private String login(String username, String password) {
Entidades.User u = null;
String r = "s";
try {
u = udao.getUser(username);
System.out.println("olaola");
} catch (Exception e) {
r = "n";
}
System.out.println(r);
System.out.flush();
if (r.equals("s") && u.checkPassword(password)) {
this.user = u;
this.auth = (u.isAdmin() ? 2 : 1);
} else {
r = "n";
}
return r;
}
What actually happens is the exception is thrown, but very happily ignored, that println executes, r is not set to "n", and then it tries to do u.checkPassword on a null.实际发生的是抛出异常,但很高兴地被忽略了,即 println 执行,r 未设置为“n”,然后它尝试在 null 上执行 u.checkPassword。 I've never been so confused in my life while coding.我一生中从未在编码时如此困惑。 Any help is appreciated任何帮助表示赞赏
Inside getUser
method, the UserNaoExiste
exception is thrown and it is caught inside that same method.在getUser
方法中,抛出UserNaoExiste
异常并在同一个方法中捕获它。
try (Connection con = DriverManager.getConnection(this.url, this.username, this.password)) {
PreparedStatement stm = con.prepareStatement("SELECT * FROM user WHERE username = ?");
stm.setString(1, username);
ResultSet rs = stm.executeQuery();
if (rs.next() == false) {
throw new Exceptions.UserNaoExiste();
}
u = new Entidades.User(rs.getString("Username"), rs.getString("Password"), rs.getString("Nick"), rs.getString("Admin"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
And in the login
method the catch statement will never execute because the exception throw by getUser
is already caught by that getUser
method.在login
方法中,catch 语句永远不会执行,因为getUser
抛出的异常已经被getUser
方法捕获了。
You can catch a specific exception SQLException
for database related exceptions instead of Exception
inside your getUser
method.您可以捕获数据库相关异常的特定异常SQLException
而不是getUser
方法中的Exception
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.