因此,我有一个方法,如果发生异常,我希望在该方法中重试操作。如果第二次发生异常,我希望在方法被另一个类调用的地方捕获异常。这是正确的做法吗?
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;
}发布于 2019-06-24 18:38:25
最好使用循环,这样就不会重复:
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
}https://stackoverflow.com/questions/56734700
复制相似问题