1

this is my main method:

public static void main(String... args) throws ClassNotFoundException {
    String[] classAndMethod = args[0].split("#");
    if (helpCmd(args)) {
        printHelpForTest(classAndMethod[1]);
        System.exit(0);
    }

    Result result = runTest(classAndMethod);
    exitIfTimeOutExceptionThrown(result);
    System.exit(result.wasSuccessful() ? 0 : 1);
}

private static void exitIfTimeOutExceptionThrown(Result result) {
    boolean isTimeOut = Iterables.filter(result.getFailures(), CodeBlockTimeOutException.class).iterator().hasNext();
    if (isTimeOut)
    {
        System.exit(2);
    }
}

which runs this junit test:

    @Test
    public void sendSearchRequest() throws Exception {

...

        setTimeOut();

...
    }

private void setTimeOut() {
    if (criticalBlockTimeOut != null) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                throw new CodeBlockTimeOutException();
                //thread.interrupt();

            }
        };
        new Timer().schedule(timerTask, Long.parseLong(criticalBlockTimeOut));
    }
}

why i see my code throws the CodeBlockTimeOutException but it main never exit with code 2?

how can I throw it to be caught in the main thread?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • possible duplicate of [Unable to catch exception from TimerTask thread](http://stackoverflow.com/questions/11448214/unable-to-catch-exception-from-timertask-thread) – Anya Shenanigans Dec 15 '14 at 15:10

1 Answers1

6

Timer event happens in another thread. main thread exits without errors. Error is logged from another. In case of exception you should set some volatile flag from the scheduled job. Wait for job to finish in the main thread and then check this flag.

Have a look here: Waiting for a Timer to finish in Java or Java: Wait for TimerTask to complete before continuing execution

Community
  • 1
  • 1
Mikhail
  • 4,175
  • 15
  • 31
  • It's not possible JUnit is running in the main thread. Other thread know nothing about testing environment. – Mikhail Dec 15 '14 at 15:12