修复错误:未报告的异常InterruptedException [英] Fixing Error: Unreported Exception InterruptedException
问题描述
我是Java的新手。我只是在搜索如何使Java程序等待,并且它说使用 Thread.sleep()
方法。但是,当我这样做时,它会出现错误:
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:
错误:未报告的异常InterruptedException;必须被捕获或声明被抛出
error: unreported exception InterruptedException; must be caught or declared to be thrown
我通过添加修复了这个问题引发了InterruptedException
到方法声明,现在它可以工作。
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?
无论如何,Draw.java的代码(使用sleep()方法):
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
}
}
并且在Square.java中(调用DS()):
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);
}
}
谢谢。
推荐答案
提供的示例演示如何执行异常调用调用链(向上调用方法调用链)。为此你的方法声明包含一个抛出InterruptedException。
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
}
添加后,尝试{} catch(){}
阻止,从方法DS中删除抛出InterruptedException。
After you added try {} catch() {}
block, remove "throws InterruptedException" from the method DS.
您可以使用换行其他行根据需要尝试{} catch(){}
阻止。阅读 Java例外。
You can wrap other lines with try {} catch() {}
block as required. Read about Java exceptions.
这篇关于修复错误:未报告的异常InterruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!