黑马程序员技术交流社区

标题: 请大家进来帮忙解决下问题!!! [打印本页]

作者: liaohongjie    时间: 2014-9-4 17:39
标题: 请大家进来帮忙解决下问题!!!
class A extends Thread
{
     public void run() //throws InterruptedException 这里不能进行声明可能有异常,因为父类方法中并没有这样声明,所以无法覆盖
     {
          int[] add = new int[50];
         
          for(int i=0; i<add.length; i++)
          {
             add[i] = i;
             try
             {
                  sleep(100);
             }
             catch(InterruptedException e)
             {
                  throw new RuntimeException(e); //这里可以不进行任何操作
             }
          }
            
          for(int i=add.length-1; i>=0; i-- )
          {
             System.out.print("  "+ currentThread().getName() + add[i]);
             try
             {
                  sleep(100);
             }
             catch(InterruptedException e)
             {
                  throw new RuntimeException(e); //这里可以不进行任何操作
             }
          }
     }
}
public class TestThread_2
{
     public static void main(String[] args)
     {
          A aa1 = new A();
          A aa2 = new A();
         
          aa1.start();
          aa2.start();
         
     }
}

上面代码是我看书时,自己想出来的代码!我的问题是上面代码中 静态方法sleep()在中断时会发生异常,在catch代码块中,为什么抛出的是RuntimeException,抛出Exception都不行,或者在catch中不写任何代码

作者: The_king丶    时间: 2014-9-4 21:07
朋友您好,我运行到可以哦!你再试试看?
作者: liaohongjie    时间: 2014-9-5 20:53
上面的代码运行时  是可以啊!但是如果这行代码改下就不行   throw new InterruptedException(e); 改成   throw  new Exception(e);就不行,而且异常  InterruptedException 是受检查异常。并不是运行时异常,为什么需要抛出运行时异常,
作者: liaohongjie    时间: 2014-9-5 20:55
The_king丶 发表于 2014-9-4 21:07
朋友您好,我运行到可以哦!你再试试看?

上面的代码运行时  是可以啊!但是如果这行代码改下就不行   throw new InterruptedException(e); 改成   throw  new Exception(e);就不行,而且异常  InterruptedException 是受检查异常。并不是运行时异常,为什么需要抛出运行时异常,




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2