Bug Fix: Unregistered InterruptedException

I am new to Java. I was just looking for how to make the Java program wait, and said that it was using the Thread.sleep() method. However, when I do this, an error occurs:

error: unregistered exception InterruptedException; must be caught or declared abandoned

I fixed this by adding throws InterruptedException to the method declaration, and now it works.

However, when I called the method, I got an error again. People say they use a throw and a catch block, but I'm not sure how to do this. Can someone help me here?

In any case, the code for Draw.java (with the 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 (call 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:%nx: %d%ny: %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.

+6
source share
2 answers

The given example demonstrates how to make an exception, pass a chain of calls (up the chain of method calls). To do this, your method declaration contains an InterruptedException throw.

An alternative approach is to handle the exception in the method in which 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 add the try {} catch() {} , remove the "throws InterruptedException" from the DS method.

You can wrap other lines with try {} catch() {} as needed. Read about Java exceptions .

+9
source

A simple streaming program that illustrates the sleep function comes with JavaThread

 class sub implements Runnable{ public void run() { System.out.println("thread are started running..."); try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e); } System.out.println("running properly....."); } public static void main(String[] args) { sub r1=new sub(); Thread t1=new Thread(r1); // with the help of start t1.start(); } } 
0
source

Source: https://habr.com/ru/post/1495026/


All Articles