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. 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.
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.
You can catch a specific exception SQLException
for database related exceptions instead of Exception
inside your getUser
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.