修复错误:未报告的exceptionInterruptedException

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

错误:未报告的exceptionInterruptedException; 必须被抓住或宣布被抛出

我通过向方法声明添加throws InterruptedException来修复它,现在它可以工作了。

但是,在调用方法时,我再次收到错误。 人们说要使用抛出和捕获块,但我不知道该怎么做。 有人可以帮我吗?

无论如何,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:%nx: %d%ny: %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); } } 

谢谢。

提供的示例演示了如何对调用链进行exception调用(向上调用方法调用链)。 为此,您的方法声明包含抛出InterruptedException。

替代方法是在它发生的方法中处理exception :在你的情况下添加

 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() {}块来包装其他行。 阅读Javaexception 。