Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
冒泡出一个异常:Java_Java_Exception - Fatal编程技术网

冒泡出一个异常:Java

冒泡出一个异常:Java,java,exception,Java,Exception,因此,我有一个方法,如果发生异常,我希望在该方法中重试该操作。如果该异常再次发生,我希望在另一个类调用该方法的地方捕获该异常。这是正确的方法吗 public OAuth2AccessToken getAccessTokenWithRefreshToken (String refreshToken) throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException ,ExecutionException {

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

    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
}
public OAuth2AccessToken getAccessTokenWithRefreshToken(字符串refreshToken)抛出OAuth2AccessTokenErrorResponse、IOException、InterruptedException、ExecutionException{
int=2;
int尝试=0;
while(尝试<最大尝试){
试一试{
返回mOAuthService.refreshAccessToken(refreshToken);
}
捕获(IOException | InterruptedException | ExecutionException e){
尝试++;
如果(尝试次数>=最大尝试次数){
投掷e;
}
}
}
返回null;//或引发异常-永远不应到达
}