java修复错误:未报告的异常InterruptedException
我是Java新手。我正在搜索如何让Java程序等待,它说使用Thread.sleep()
方法。但是,当我这样做时,会出现一个错误:
error: unreported exception InterruptedException; must be caught or declared to be thrown
我通过在方法声明中添加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
}
}
在广场上。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);
}
}
谢谢
# 1 楼答案
提供的示例演示了如何向上传递调用链(向上传递方法调用链)。为此,您的方法声明包含一个throws InterruptedException
另一种方法是处理发生的方法中的异常:在您的情况下,添加
添加
try {} catch() {}
块后,从方法DS中删除“throws InterruptedException”您可以根据需要使用
try {} catch() {}
块包装其他行。阅读Java exceptions# 2 楼答案
JavaThread附带了一个简单的线程程序,它演示了睡眠功能