【问题标题】:Fixing Error: Unreported Exception InterruptedException修复错误:未报告的异常 InterruptedException
【发布时间】:2013-08-02 20:07:13
【问题描述】:

我是 Java 新手。我只是在搜索如何让 Java 程序等待,它说使用 Thread.sleep() 方法。但是,当我这样做时会出现错误:

错误:未报告的异常InterruptedException;必须被抓住或宣布被扔掉

我通过在方法声明中添加throws InterruptedException 解决了这个问题,现在它可以工作了。

但是,当调用该方法时,我再次收到错误消息。人们说要使用 throw and catch 块,但我还不知道该怎么做。有人可以帮我吗?

无论如何,Draw.java 的代码(使用 sleep() 方法):

package graphics.utilities;

public class Draw {
  public static void DS(int[] c)
    throws InterruptedException {
    \\ .. Drawing Algorithms
    Thread.sleep(2000);
    \\ .. More Drawing Algorithms
  }
}

在 Square.java 中(调用 DS()):

package graphics.shapes;

import graphics.utilities.*;

public class Square implements Graphics {
  int x1,y1,s;
  public Square(int x1,int y1,int s) {
    this.x1 = x1;
    this.y1 = y1;
    this.s = s;
  }
  public void GC() {
    System.out.printf("Square Coordinates:%n Start Point:%n  x: %d%n  y: %d%n Height/Width: %d%n%n" , this.x1,this.y1,this.s);
  }
  public void D() {
    int x2 = x1 + s;
    int y2 = y1;
    int x3 = x1 + s;
    int y3 = y1 + s;
    int x4 = x1;
    int y4 = y1 + s;

    int[] c = {x1,y1,x2,y2,x3,y3,x4,y4};
    Draw.DS(c);
  }
}

谢谢。

【问题讨论】:

    标签: java exception


    【解决方案1】:

    提供的示例演示了如何将异常向上传递调用链(向上传递方法调用链)。为此,您的方法声明包含 throws InterruptedException。

    另一种方法是在它发生的方法中处理异常:在你的情况下添加

    try 
    {
        Thread.sleep(2000);
    } 
    catch(InterruptedException e)
    {
         // this part is executed when an exception (in this example InterruptedException) occurs
    }
    

    添加try {} catch() {} 块后,从方法 DS 中删除“throws InterruptedException”

    您可以根据需要使用try {} catch() {} 块包装其他行。阅读Java exceptions

    【讨论】:

      【解决方案2】:

      JavaThread自带的简单的线程程序说明睡眠功能

      class sub implements Runnable{
       public void run()
       {
           System.out.println("thread are started running...");
           try
           {
                 Thread.sleep(1000);
            }
            catch(Exception e)
            {
                System.out.println(e);
             }
            System.out.println("running properly.....");
       }
       public static void main(String[] args) 
      {
          sub r1=new sub();
          Thread t1=new Thread(r1);
      
          // with the help of start
          t1.start();  } }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多