For Java, we cannot simply catch exception from other thread.
For example, with JUnit, we want to catch an exception from other threads in a unit test. Cannot do that directly.
But we can use stdout as a "bridge".
// In the other thread
// use slf4j Logger
throw new Exception("exception message");
Logger.error("exception message");
With slf4j logger, the exception message will be showed in console when doing unit test.
Then we can redirect the system out to PrintStream.
// Unit test
public class Test {
PrintStream console = null; // set output stream
PrintStream stdout = System.out;
ByteArrayOutputStream bytes = null; // buffer the messages from console
@Before
public void reset() {
bytes = new ByteArrayOutputStream(); // assign memory
System.setOut(new PrintStream(bytes)); // redirect the message from Console to bytes
}
@After
public void tearDown() {
System.setOut(stdout);
}
@Test
public void catchExceptionMessage() {
assertTrue(bytes.toString().contains("key message"));
}
}
BTW, there is a useful way to catch un-caught exception within the SAME thread, good to know but doesn't relate to this issue.
Thread.UncaughtExceptionHandler
网友评论