1

So I have a method where if an exception occurs, I want to retry the operation within the method. If the exception happens a second time, I want the exception be caught where the method is called by another class. Is this the correct way to do it?

    public OAuth2AccessToken getAccessTokenWithRefreshToken  (String refreshToken) throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException ,ExecutionException  {
    try {
        System.out.println("trying for the first time");
        OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(refreshToken);
        return mAccessToken;
     catch (IOException | InterruptedException | ExecutionException e) {
        try {
            System.out.println("trying for the second time");
            OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(refreshToken);
        }  catch (IOException | InterruptedException | ExecutionException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
            throw e2;
        }
    }
    return mAccessToken;
}
Daniel Haughton
  • 1,085
  • 5
  • 20
  • 45

1 Answers1

1

It's better to use a loop, in order not to repeat yourself:

public OAuth2AccessToken getAccessTokenWithRefreshToken  (String refreshToken) throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException ,ExecutionException {
    int maxAttempts = 2;
    int attempt = 0;
    while (attempt < maxAttempts) {
        try {
            return mOAuthService.refreshAccessToken(refreshToken);
        }
        catch (IOException | InterruptedException | ExecutionException e) {
            attempt++;
            if (attempt >= maxAttempts) {
                throw e;
            }
        }
    }
    return null; // or throw an exception - should never be reached
}
Eran
  • 387,369
  • 54
  • 702
  • 768