A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© liaohongjie 中级黑马   /  2014-9-4 17:39  /  1008 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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中不写任何代码

3 个回复

倒序浏览
朋友您好,我运行到可以哦!你再试试看?
回复 使用道具 举报
上面的代码运行时  是可以啊!但是如果这行代码改下就不行   throw new InterruptedException(e); 改成   throw  new Exception(e);就不行,而且异常  InterruptedException 是受检查异常。并不是运行时异常,为什么需要抛出运行时异常,
回复 使用道具 举报
The_king丶 发表于 2014-9-4 21:07
朋友您好,我运行到可以哦!你再试试看?

上面的代码运行时  是可以啊!但是如果这行代码改下就不行   throw new InterruptedException(e); 改成   throw  new Exception(e);就不行,而且异常  InterruptedException 是受检查异常。并不是运行时异常,为什么需要抛出运行时异常,
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马