首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >冒泡异常: Java

冒泡异常: Java
EN

Stack Overflow用户
提问于 2019-06-24 18:31:39
回答 1查看 439关注 0票数 1

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

代码语言:javascript
复制
    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;
}
EN

回答 1

Stack Overflow用户

发布于 2019-06-24 18:38:25

最好使用循环,这样就不会重复:

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56734700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档