所以我有一个方法,如果发生异常,我想重试该方法中的操作。如果该异常第二次发生,我希望在另一个类调用该方法的地方捕获该异常。这是正确的方法吗?
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;
}
答案 0 :(得分:1)
最好使用循环,以免重复自己:
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
}