I'm new to Java. I was just searching how to make a Java program wait, and it said to use the Thread.sleep() method. However, when I do this it comes up with an error:
error: unreported exception InterruptedException; must be caught or declared to be thrown
I fixed that by adding throws InterruptedException to the method declaration, and now it works.
However, when calling the method, I got the error again. People say to use a throw and catch block, but I'm not sure how to do that yet. Could somebody help me here?
Anyways, code for Draw.java (with sleep() method):
package graphics.utilities;
public class Draw {
public static void DS(int[] c)
throws InterruptedException {
\\ .. Drawing Algorithms
Thread.sleep(2000);
\\ .. More Drawing Algorithms
}
}
And in Square.java (calling 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);
}
}
Thanks.
解决方案
Provided example demonstrates how to do exception pass up the call chain (up the method call chain). For this your method declaration contains a throws InterruptedException.
Alternative approach is to handle exception in the method it occurred: in your case add
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
// this part is executed when an exception (in this example InterruptedException) occurs
}
After you added try {} catch() {} block, remove "throws InterruptedException" from the method DS.
You can wrap other lines with try {} catch() {} block as required. Read about Java exceptions.