java 如何处理Java中的超时异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13465930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:51:46  来源:igfitidea点击:

How to deal with timeout exception in Java?

javatimeout

提问by jerry_sjtu

Here is my code:

这是我的代码:

 private void synCampaign() {
    List<Campaign> campaigns;
    try {
        campaigns = AdwordsCampaign.getAllCampaign();
        for(Campaign c : campaigns) 
            CampaignDao.save(c);
    } catch (ApiException e) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synCampaign();
        e.printStackTrace();
    } catch (RemoteException e) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synCampaign();
        e.printStackTrace();
    }

}

AdwordsCampaign.getAllCampaign()tries to get some remote resource. This may throw a RemoteExceptionbecause the internet connection times out. When the exception is caught, I just want the thread to sleep for a while, then try to get the remote resource again.

AdwordsCampaign.getAllCampaign()尝试获取一些远程资源。这可能会抛出一个RemoteException因为互联网连接超时。当异常被捕获时,我只想让线程休眠一段时间,然后再次尝试获取远程资源。

Is there a problem with my code? Or is there a better way?

我的代码有问题吗?或者,还有更好的方法?

回答by leonbloy

Nothing really wrong, but the (potentially infinite) retry loop with recursion (and the stack growing) makes me a little nervous. I'd write instead:

没有什么错,但是(可能是无限的)带有递归的重试循环(和堆栈增长)让我有点紧张。我会写:

private void synCampaignWithRetries(int ntries, int msecsRetry) {
    while(ntries-- >=0 ) {
       try {
         synCampaign();
         return; // no exception? success
       } 
      catch (ApiException e ) {
           // log exception?
      }
      catch (RemoteException e ) {
           // log exception?
      }
      try {
           Thread.sleep(msecsRetry);
      } catch (InterruptedException e1) {
           // log exception?
      }
   }
   // no success , even with ntries - log?
}

private void synCampaign() throws ApiException ,RemoteException {
    List<Campaign> campaigns = AdwordsCampaign.getAllCampaign();
    for(Campaign c : campaigns) 
            CampaignDao.save(c);
}

回答by Yogendra Singh

This looks OK except the repetition of code in catch block(be sure of number of retries you want). You may want to create a private method to handle your exception as below:

这看起来不错,除了 catch 块中的代码重复(确保你想要的重试次数)。您可能希望创建一个私有方法来处理您的异常,如下所示:

    private void synCampaign() {
        List<Campaign> campaigns;
        try {
            campaigns = AdwordsCampaign.getAllCampaign();
            for(Campaign c : campaigns) 
                CampaignDao.save(c);
        } catch (ApiException e) {
            e.printStackTrace();
            waitAndSync();
        } catch (RemoteException e) {
            e.printStackTrace();
            waitAndSync();
        }

    }

    private void waitAndSync(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synCampaign();
    }

回答by Kaushik Lele

You indeed cannot catch it as a SocketTimeoutException. What is possible is to catch the RemoteException, retrieve it's cause and check if that's an instanceof SocketTimeoutException.

您确实无法将其作为 SocketTimeoutException 捕获。可能的是捕获 RemoteException,检索它的原因并检查它是否是 SocketTimeoutException 的实例。

    try{
             // Your code that throws SocketTimeoutException

        }catch (RemoteException e) {
          if(e.getCause().getClass().equals(SocketTimeoutException.class)){
             System.out.println("It is SocketTimeoutException");
             // Do handling for socket exception
            }else{
              throw e;
            }
        }catch (Exception e) {
           // Handling other exception. If necessary
        }