gpt4 book ai didi

java - 为什么我的异常需要放在 try/catch 中?

转载 作者:行者123 更新时间:2023-12-01 18:36:29 25 4
gpt4 key购买 nike

我正在尝试从数据库中获取信息。并检查用户名是否已经存在我正在使用谷歌云Firestore数据库。我将该方法声明为抛出我创建的异常。当我尝试调用异常的抛出时,它告诉我需要将其放入 try/catch block 中。我想知道为什么,因为我做了类似的事情(但是和我的老师一起使用 sqlite,它工作得很好)

我的代码:

@Override
public void isUserExists(final String username, String email) throws UserExistsException {
Log.e(TAG, "isUserExists: in start of method" );
// gets the document reference
CollectionReference usersRef = db.collection(COLLECTION_NAME);
//Creates and returns a new Query with the additional filter that documents must contain the specified field and the value should be equal to the specified value.
Query query = usersRef.whereEqualTo(KEY_USERNAME, username);
//Executes the query and returns the results as a QuerySnapshot.
// QuerySnapshot = A QuerySnapshot contains the results of a query. It can contain zero or more DocumentSnapshot objects. (is an iterable)
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
Log.e(TAG, "isUserExists: in the onComplete" );
//A DocumentSnapshot contains data read from a document in your Cloud Firestore database.
if (task.isSuccessful()) {
Log.e(TAG, "isUserExists: in the if statement" );
for (DocumentSnapshot item : task.getResult()) {
Log.e(TAG, "isUserExists: in for loop" );
//getString() = Returns the value of the field as a String.
String user = item.getString(KEY_USERNAME);
if (user.equals(username)) {
//this throw line will not compile
throw new UserExistsException();
}
}
}
}
});
}

我正在实现这个接口(interface):

public interface IUser {

void isUserExists(String username, String email) throws UserExistsException;
void isPassesMatch(String password, String rePass) throws PasswordMismatchException;
void checkLength(String username, String password) throws PasswordLengthException, UserNameLengthException;
void checkUserCred(String username, String password) throws UserCredentialException;
void registerUser (String username, String password, String email) throws UserException;
}

我在类里面和老师做的类似的事情:

 @Override
public void userExists() throws UserExistsException {
String sqlStatement = "SELECT * FROM " + TABLE_NAME + " WHERE userName = '" + this.userName + "'";
Cursor res = db.rawQuery(sqlStatement, null);
if(res.moveToFirst()){
throw new UserExistsException();
}
}

编辑(添加我抛出的异常):

public class UserExistsException extends UserException {

public UserExistsException(String message) {
super(message);
}

public UserExistsException() {
super("User Already Exists");
}
}

另一个编辑(添加处理方法及其异常的位置):

private void register() {
String uName = regActEtUname.getText().toString();
String uPass = regActEtPass.getText().toString();
String rePass = regActEtRePass.getText().toString();
String uEmail = regActEtEmail.getText().toString();

try {
// checks if the user exissts
utils.isUserExists(uName,uEmail);
//checks if the length is fulfilled
utils.checkLength(uName,uPass);
//checks if the passwords match
utils.isPassesMatch(uPass, rePass);
//registers the user
utils.registerUser(uName,uPass,uEmail);

} catch (UserExistsException | PasswordLengthException | UserNameLengthException | PasswordMismatchException e) {
Log.e("fbdb", "register: " + e.getMessage() );
TastyToast.makeText(context,e.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR);
} catch (UserException e) {
Log.e("regErr", "register: " + e.getMessage() );
} catch (Exception e) {
Log.e("regErr", "register: " + e.getMessage() );
}
}

最佳答案

试试这个代码:

@Override
public void isUserExists(final String username, String email) throws
UserExistsException {

CollectionReference allUsersRef = db.collection(COLLECTION_NAME);
Query userNameQuery = allUsersRef.whereEqualTo(KEY_USERNAME, username);
userNameQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.exists()) {
String userName = document.getString(username);
Log.d(TAG, "username already exists");
} else {
Log.d(TAG, "username does not exists");
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});
}

如果对您有帮助,请告诉我。

关于java - 为什么我的异常需要放在 try/catch 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60030850/

25 4 0