实现了Runnable接口的run()方法,但是run()方法中所调用的方法会抛出异常,不想让异常在run()方法中消失,想让他继续抛出,最后在启动线程处捕获,具体请看示例代码.
顺便请讲一下,线程的异常处理./**
 * 实现Runnable接口的类SubThread
 */
  public class SubThread implements Runnable{
     public void run(){//编译错误 try..catch..
         test();//怎样让该方法的异常继续往上抛?
     }
     public void test() throws Exception {
        throw new Exception("Thread Exception!");
     }
  }
/**
 * 启动线程的类
 */
 public class TestSubThread {
    public static void testST(){
        SubThread subThread = new SubThread();
        Thread thread = new Thread(subThread);
        thread.start();//此处启动线程,异常怎么处理?
    }
 }

解决方案 »

  1.   

    不同线程的函数调用堆栈是不同的 所以直接实现你的想法是不可能的
    你可以变通一下 做一个异常处理的后台线程 循环监听一个一个异常列表 当其他线程中有异常出现时(通过在线程的run函数中加try..catch...捕获),将捕获到的异常加入这个异常列表 然后异常处理线程就可以处理这个异常了
      

  2.   

    public void run(){
    synchronized(this){
    try{
    Thread.sleep(2000);
    }catch(InterruptedException e){
    throw new RuntimeException(e);
    }
    int a = 1/0;
    }
    }
      

  3.   

    请大家到我的计算机论坛看看,随便给提点意见,人多力量大嘛,注册一下,回答几个一直我都不会的问题,肯定我会给大家奖励的,网址是,http://java.cc.topzj.com/
      

  4.   

    TO:tomkai(我不是苹果) ,不知道这样一来理解多不对?使用synchronized和不使用的区别?谢谢~
      public void run(){
             try{
        Thread.sleep(1000);
                 test();
    }catch(InterruptedException e){
        new RuntimeException(e);
    }catch(){Exception e){
                 new RuntimeException(e);
             }
         }
      

  5.   

    哦...这段是我从我写的代码里COPY过来的..synchronized是多线程操作时候的同步锁机制...你现在是单线程这一段不需要的话可以去年..
    sleep是睡眠该线程一定时间...将CPU交给其它线程...该线程进入等待池..在你这里也可以不要
      

  6.   

    BlockingQueue bq; // 当队列为空时 get 将等待。示意代码。public void run() {
      try {
        do();
      } catch (Throwable t) {
        bq.add(t);
      }
    }// 异常处理线程
    public void run() {
      while (true) {
        Throwable t = bq.get(0);
        try {
          throw t;
        } catch (...)
      }
    }