首页 > 解决方案 > 冒泡一个异常:Java

问题描述

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

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

标签: javaexception

解决方案


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

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
}

推荐阅读