java interruptedexception,修复错误:未报告的异常InterruptedException

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值