Spark323
Spark323

Reputation: 1585

Exception thrown inside an anonymous inner class not caught

I have a method that has an anonymous inner class. I want to throw an unchecked exception from inside the anonymous inner class, and catch it outside of the class. I'm having trouble doing this.

@Override
public void showAchievements(){

    androidLauncher.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                loadingView.showLoadingView();
                Games.getAchievementsClient(androidLauncher, signedInAccount)
                    .getAchievementsIntent()
                    .addOnSuccessListener(new OnSuccessListener<Intent>() {
                        @Override
                        public void onSuccess(Intent intent) {
                            throw new RuntimeException("Test exception");
                        }
                    });
            }  catch (Exception e){
                // Not catching
            }
        }
    });
}

My exception is not being caught. What am I doing wrong?

Upvotes: 4

Views: 495

Answers (2)

Andy Turner
Andy Turner

Reputation: 140299

You are throwing an exception in a callback method.

Either the callback method is never invoked, it is not invoked synchronously, or the code that ultimately invokes the callback method is catching it.

Without seeing more of your code, it is impossible to say which.

Upvotes: 2

Dorian Gray
Dorian Gray

Reputation: 2980

This is because you have to move your try-catch-statement inside the onSuccess method. The listener is called at a later point.

Upvotes: 0

Related Questions