简体   繁体   中英

Java exception not being caught?

I´ve got the following code in a class called UserRepository , that throws an Exception:

public void addUser(final User user) throws  IllegalArgumentException {
        final String encodedUserId = Email.encodeID(user.getEmail().getAddress());
        firebaseUsersRef.child(encodedUserId).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    throw new IllegalArgumentException(USER_ALREADY_EXISTS);
                } else {
                    Firebase firebaseUserReference = firebaseRef.child(USERS_TABLE).child(encodedUserId);
                    firebaseUserReference.setValue(user);
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                throw new IllegalArgumentException(FIREBASE_ERROR);
            }
        });
    }

I am using it in RegisterActivity.java , like this:

public void saveUser(){
     saveUserToDb();
}

private void saveUser(User user) {
        boolean savedUser = false;
        try {
            userRepository.addUser(user);
            savedUser = true;
        } catch (IllegalArgumentException iae) {
            if (iae.getMessage().equals(UserRepository.USER_ALREADY_EXISTS)) {
                showToast(getResources().getString(R.string.user_already_exists));
            } else if (iae.getMessage().equals(UserRepository.FIREBASE_ERROR)) {
                showToast(getResources().getString(R.string.firebase_error));
            }
        } finally {
            if (savedUser) {
                showToast(getResources().getString(R.string.new_user_created));
            }
        }
    }

So I am catching the exception, if happens. However, for some reason, the exception is not being caught .

Any hint?

Thanks.

EDIT :

Here´s my stacktrace:

 04-27 09:56:34.984 4741-4741/app E/AndroidRuntime: FATAL EXCEPTION: main
   Process: app, PID: 4741
   java.lang.IllegalArgumentException: User already exists
       at app.repository.UserRepository$1.onDataChange(UserRepository.java:33)
       at com.firebase.client.Query$1.onDataChange(Query.java:144)
       at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:56)
       at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
       at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5417)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-27 09:57:39.773 4741-4747/app W/art: Suspending all threads took: 6.473ms

Implementing Exceptions and try catch is very heavy task and one should always avoid using try catch. Instead, you can implement the same thing using custom interface and trigger the function according to your requirements. Please see the sample code here:

public interface CustomInterface {
  void handleResult(String response);
}

Now change your addUser method to:

public void addUser(final User user, CustomInterface customInterface){
    final String encodedUserId = Email.encodeID(user.getEmail().getAddress());
    firebaseUsersRef.child(encodedUserId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.exists()) {
                customInterface.handleResult(USER_ALREADY_EXISTS); // I assume this is String
            } else {
                Firebase firebaseUserReference = firebaseRef.child(USERS_TABLE).child(encodedUserId);
                firebaseUserReference.setValue(user);
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            customInterface.handleResult(FIREBASE_ERROR); // I assume this is String
        }
    });
}

Then finally, change your saveUser Method to:

private void saveUser(User user) {
    boolean savedUser = false;
    userRepository.addUser(user, new CustomInterface() {
                @Override
                public void handleResult(String response) {
                    if (response.equals(UserRepository.USER_ALREADY_EXISTS)) {
                        showToast(getResources().getString(R.string.user_already_exists));
                    } else if (response.equals(UserRepository.FIREBASE_ERROR)) {
                        showToast(getResources().getString(R.string.firebase_error));
                    }
                    // And Do whatever you want to do, here in this method
                }
            });
}

I hope now you'll be able to understand this.

Try like this:

public void addUser(final User user) {
            final String encodedUserId = Email.encodeID(user.getEmail().getAddress());
            firebaseUsersRef.child(encodedUserId).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    if (snapshot.exists()) {
                        try {
                            throw new IllegalArgumentException(USER_ALREADY_EXISTS);
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Firebase firebaseUserReference = firebaseRef.child(USERS_TABLE).child(encodedUserId);
                        firebaseUserReference.setValue(user);
                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    try {
                        throw new IllegalArgumentException(FIREBASE_ERROR);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();;
                    }
                }
            });
        }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM