Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 修复错误:未报告的异常InterruptedException_Java_Exception - Fatal编程技术网

Java 修复错误:未报告的异常InterruptedException

Java 修复错误:未报告的异常InterruptedException,java,exception,Java,Exception,我是Java新手。我正在搜索如何让Java程序等待,它说使用Thread.sleep()方法。但是,当我这样做时,会出现一个错误: 错误:未报告的异常InterruptedException;必须被抓住或宣布被抛出 我通过在方法声明中添加抛出InterruptedException修复了这个问题,现在它可以工作了 然而,当调用该方法时,我再次遇到了错误。人们说要使用抛接球拦网,但我还不知道怎么做。有人能帮我吗 无论如何,Draw.java的代码(使用sleep()方法): 在Square.jav

我是Java新手。我正在搜索如何让Java程序等待,它说使用
Thread.sleep()
方法。但是,当我这样做时,会出现一个错误:

错误:未报告的异常InterruptedException;必须被抓住或宣布被抛出

我通过在方法声明中添加
抛出InterruptedException
修复了这个问题,现在它可以工作了

然而,当调用该方法时,我再次遇到了错误。人们说要使用抛接球拦网,但我还不知道怎么做。有人能帮我吗

无论如何,Draw.java的代码(使用sleep()方法):

在Square.java中(调用DS()):


谢谢。

提供的示例演示了如何向上传递调用链(向上传递方法调用链)的异常。为此,您的方法声明包含一个throws InterruptedException

另一种方法是处理发生的方法中的异常:在您的案例中,添加

try 
{
    Thread.sleep(2000);
} 
catch(InterruptedException e)
{
     // this part is executed when an exception (in this example InterruptedException) occurs
}
添加
try{}catch(){}
block后,remove从方法DS中抛出InterruptedException“


您可以根据需要使用
try{}catch(){}
块包装其他行。阅读。

简单线程程序,该程序演示了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();  } }
try 
{
    Thread.sleep(2000);
} 
catch(InterruptedException e)
{
     // this part is executed when an exception (in this example InterruptedException) occurs
}
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();  } }