我是Java的新手.我只是在搜索如何使Java程序等待,并说它使用该Thread.sleep()方法.但是,当我这样做时,它会出现错误:
错误:未报告的异常InterruptedException; 必须被抓住或宣布被抛出
我通过添加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
}
}
Run Code Online (Sandbox Code Playgroud)
在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);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
提供的示例演示了如何执行异常传递调用链(在方法调用链上).为此,您的方法声明包含抛出InterruptedException.
替代方法是在它发生的方法中处理异常:在你的情况下添加
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
// this part is executed when an exception (in this example InterruptedException) occurs
}
Run Code Online (Sandbox Code Playgroud)
添加try {} catch() {}块后,从方法DS中删除"throws InterruptedException".
您可以try {} catch() {}根据需要使用块包装其他行.阅读Java异常.
| 归档时间: |
|
| 查看次数: |
26380 次 |
| 最近记录: |