在下面的示例代码中,如果 testMethod() 通过 main() 运行,它会按预期工作,但如果它通过 JUNIT 运行,则不会调用 MyUncaughtExceptionHandler。
对此有什么解释吗?
package nz.co.test;
import java.lang.Thread.UncaughtExceptionHandler;
import org.junit.Test;
public class ThreadDemo {
private void testMethod() {
Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
Object b = null;
// Cause a NPE
b.hashCode();
}
@Test
public void testJunit() {
// Run via JUnit and MyUncaughtExceptionHandler doesn't catch the Exception
testMethod();
}
public static void main(String[] args) {
// Run via main() works as expected
new ThreadDemo().testMethod();
}
static class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("I caught the exception");
}
}
}