相关疑难解决方法(0)

110
推荐指数
9
解决办法
15万
查看次数

处理ExecutionException的原因

假设我有一个类定义了要完成的大块工作,可以产生几个已检查的异常.

class WorkerClass{
   public Output work(Input input) throws InvalidInputException, MiscalculationException {
      ...
   }
}
Run Code Online (Sandbox Code Playgroud)

现在假设我有一个可以调用这个类的GUI.我使用SwingWorker委派任务.

Final Input input = getInput();
SwingWorker<Output, Void> worker = new SwingWorker<Output, Void>() {
        @Override
        protected Output doInBackground() throws Exception {
            return new WorkerClass().work(input);
        }
};
Run Code Online (Sandbox Code Playgroud)

如何处理从SwingWorker抛出的可能异常?我想区分我的worker类的异常(InvalidInputException和MiscalculationException),但ExecutionException包装器使事情变得复杂.我只想处理这些异常 - 不应该捕获OutOfMemoryError.

try{
   worker.execute();
   worker.get();
} catch(InterruptedException e){
   //Not relevant
} catch(ExecutionException e){
   try{
      throw e.getCause(); //is a Throwable!
   } catch(InvalidInputException e){
      //error handling 1
   } catch(MiscalculationException e){
      //error handling 2
   }
}
//Problem: Since a Throwable is thrown, …
Run Code Online (Sandbox Code Playgroud)

java swingworker executionexception

7
推荐指数
1
解决办法
1万
查看次数

是否可以使java方法超时?

我需要执行ping Web服务来检查我是否已连接到端点,并且Web服务服务器一切正常。

这有点愚蠢,但我必须为此打电话给网络服务。问题是,当我调用stub.ping(request)和我没有连接时,它会继续尝试执行此代码一分钟……然后返回false。

如果无法ping通,是否可以在1秒后使此超时?

public boolean ping() {
        try {
            PingServiceStub stub = new PingServiceStub(soapGWEndpoint);
            ReqPing request = new ReqPing();

            UserInfo userInfo = new UserInfo();
            userInfo.setName(soapGWUser);
            userInfo.setPassword(soapGWPassword);
            ApplicationInfo applicationInfo = new ApplicationInfo();
            applicationInfo.setConfigurationName(soapGWAppName);

            stub.ping(request);

            return true;
        } catch (RemoteException | PingFault e) {
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

java

5
推荐指数
1
解决办法
127
查看次数