gpt4 book ai didi

java - 冒泡异常 : Java

转载 作者:行者123 更新时间:2023-11-30 05:35:27 27 4
gpt4 key购买 nike

所以我有一个方法,如果发生异常,我想重试该方法内的操作。如果异常第二次发生,我希望在另一个类调用该方法的地方捕获异常。这是正确的方法吗?

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

最佳答案

最好使用循环,以免重复:

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
}

关于java - 冒泡异常 : Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56734700/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com