java - 冒泡异常 : Java

标签 java exception

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

    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/

相关文章:

JavaFx通过拖放的方式用一条线连接两个子节点

java - 如何在 Java 中抛出一般异常?

C++:main() 未捕获的异常的自定义格式

java - 具有包含 HTML 代码的 JLabel 节点的 JTree 在展开节点时抛出异常

exception - 升级到.net core 2.2之后,通过EF插入失败并出现错误

java - 如何从 Java 中的重写方法传播异常

java - 在java中删除文件,同时在其他线程中上传文件

java - 密码验证不适用于特定序列

Java - 括号问题

php - 队列 worker 的 Laravel 异常处理程序