1、试用Thread.UncaughtExceptionHandler类捕获RuntimeException,并记录异常信息。
public class UncaughtExceptionLogger implements Thread.UncaughtExceptionHandler {
private Log log = LogFactory.getLog(this.getClass());
public void uncaughtException(Thread thead, Throwable e) {
System.err.println( "uncaughtException: threadName=" + thead + ",msg=" + e.getMessage() );
}
public static void regDefault() {
Thread.setDefaultUncaughtExceptionHandler( new UncaughtExceptionLogger() );
}
}
2、应用实例
public class ThreadTest extends Thread {
public ThreadTest(){
super("threadTest");
UncaughtExceptionLogger.regDefault();
}
@Override
public void run(){
String str = null;
str.toString();
while(!Thread.currentThread().isInterrupted()){
System.out.println("not Interrupted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] strs){
ThreadTest test = new ThreadTest();
test.start();
}
}