基本的Java异常处理

时间:2014-04-08 09:41:18

标签: java concurrency

考虑以下代码

class work {
    do_something() {
        try {
            // so something
        } catch (Throwable t) {/* operation alpha */
        }//
    }
}

class thread_instance implements Runnable {
    work w;

    public void run() {
        try {
            w.do_something();
        } catch (Throwable t) {/* operation beta */
        }//
    }
}

稍后我想创建一个帖子(thread_instance),如果出现某些条件,可能会取消该帖子,并且我会向thread_instance发出信号,以便到达operation beta

class call_thread {
    static public void main(String...main){
          Thread tx=new Thread(new thread_instance());
          tx.start();
          //....
          if(<<some condition>>){tx.stop();} //tries to tell thread_instance about stop command
         }
}

但由于word#do_something(void)调用了thread_instance并且能够捕获任何异常,因此无论如何都不会调用操作测试版。

问题:

如何通过thread_instance#run(void)方法确定是否存在异常/错误,而内部调用(word#do_something(void))是否捕获了异常?并假设内部调用不会抛出更高级别的异常。

1 个答案:

答案 0 :(得分:0)

这可能是您正在寻找的:

import java.lang.Thread.UncaughtExceptionHandler;

public class ThreadExceptions {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            public void run() {
                throw new NullPointerException();//Where your exception will be thrown
            }
        };
        thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {//Creates a default handler for the thread
            @Override
            public void uncaughtException(Thread arg0, Throwable arg1) {
                arg1.printStackTrace();//Do whatever you want with the exception here
            }
        });
        thread.start();
    }
}