2013-08-02 198 views
4

我是Java新手。我只是在搜索如何让Java程序等待,并且它说要使用Thread.sleep()方法。然而,当我这样做就想出了一个错误:修复错误:未报告异常中断异常

error: unreported exception InterruptedException; must be caught or declared to be thrown

我固定,通过增加throws InterruptedException的方法声明,而现在它的工作原理。

但是,当调用该方法时,我再次得到错误。人们说要使用throw和catch块,但我不确定如何去做。有人可以帮我吗?

不管怎么说,对Draw.java代码(有睡眠()方法):

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); 
    } 
} 

感谢。

+0

本文可能会帮助您理解此线程管理机制:[您如何处理InterruptedException?](http://www.yegor256.com/2015/10/20/interrupted-exception.html) – yegor256

回答

7

提供的示例演示如何执行异常传递调用链(在方法调用链中)。为此,您的方法声明包含一个抛出的InterruptedException。

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

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

当你添加try {} catch() {}块,删除“抛出InterruptedException的”从方法DS

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