简体   繁体   English

在Java中无需执行程序即可调用

[英]Callable without executor in java

import java.util.concurrent.Callable;
import java.io.IOException;

public class HelloWorld{

 public static void main(String []args){
    Callable<Void> callable = new Callable<Void>()
    {
        public Void call() throws IOException
        {
            return null;
        }

    };
    try
    {
        callable.call();
    }
    catch(IOException e)
    {}
 }
}

Here I get error "unreported exception Exception". 在这里,我得到错误“未报告的异常Exception”。 I don't want to use generic exception Exception. 我不想使用通用异常Exception。 What to do? 该怎么办?

The Callable interface explicitly declares that the call() method may throw any Exception. Callable接口显式声明call()方法可以引发任何Exception。 If you use the interface, you must catch the exception. 如果使用该接口,则必须捕获异常。

If you aren't using executors, you might be able to define your own interface: 如果您不使用执行程序,则可以定义自己的接口:

public interface IOTask
{
    public void call() throws IOException;
}

And instead of making a callable, make an IOTask instead. 而不是使之成为可调用的,而是使一个IOTask。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM