Java异常没被捕获?

时间:2016-04-27 09:48:07

标签: java android oop exception try-catch

我在名为UserRepository的类中得到以下代码,它抛出异常:

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);
            }
        });
    }

我在RegisterActivity.java中使用它,就像这样:

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));
            }
        }
    }

所以如果发生的话,我正在捕捉异常。 但是,出于某种原因,异常没有被捕获

任何提示?

感谢。

修改

这是我的堆栈跟踪:

 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

2 个答案:

答案 0 :(得分:2)

实现异常并尝试捕获是非常繁重的任务,应始终避免使用try catch。相反,您可以使用自定义界面实现相同的功能,并根据您的要求触发功能。请在此处查看示例代码:

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

现在将addUser方法更改为:

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
        }
    });
}

最后,将saveUser方法更改为:

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
                }
            });
}

我希望你现在能够理解这一点。

答案 1 :(得分:-1)

试试这样:

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();;
                    }
                }
            });
        }