Java TimerTask

public static void main(String[] args) throws Exception    {  


    Timer timer = new Timer();
    timer.schedule(new TimerTask() { 

   Document doc = Jsoup.connect("http://www.oschina.net/").get();
    public void run(){

    Elements t = doc.select("table");

    String linkText = t.text();      
    System.out.println(linkText);
   }

    },1000,5000);
}  

为什么上面的代码编译正常,下面的就不行了?

public static void main(String[] args) throws Exception    {  


    Timer timer = new Timer();
    timer.schedule(new TimerTask() { 


    public void run(){
    Document doc = Jsoup.connect("http://www.oschina.net/").get();
    Elements t = doc.select("table");

    String linkText = t.text();      
    System.out.println(linkText);
   }

    },1000,5000);
}  

这一句移了一个位置
Document doc = Jsoup.connect("http://www.oschina.net/").get();

编译错误:

Exception in thread "Timer-0" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at bitcoin.aaa$1.run(aaa.java:25)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)

阅读 3.4k
1 个回答

Jsoup.connect("http://www.oschina.net/").get();
这行代码有网络IO操作,按照java的习惯,应该抛出IOException,但是run方法是override的,
不能声明抛出IOException,必须在run方法内catch这个异常。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题