异常测试的控制台输出通常会有所不同,

时间:2018-10-26 10:22:33

标签: java testing exception

我正在运行一些样本Exception测试代码,但我不确定为什么,但是几乎每次运行时,都会遇到不同的输出。

主要方法:

public class LocalExceptionTest {
private static void numberTest(int num) {
    boolean valid = false;

    try {
        if (num < 0 || num > 9) {
            throw new RangeException("out of range");
        }

        else
            valid = true;
    }
    // specialised exceptions must come first (otherwise the asbtract
    // exception will always get caught)
    catch (RangeException e) {
        System.err.println(e.getMessage());
    }
    // catch any other unexpected exception
    catch (Exception ex) {
        // nothing much we can do so just print a stack trace and continue
        ex.printStackTrace();
    } finally {
        System.out.println("always do this");
    }

    if (valid)
        System.out.println("valid data");
}

public static void main(String args[]) {
    numberTest(5);
    numberTest(12);
    numberTest(0);
    numberTest(-1);
}

还有一个例外:

static class RangeException extends RuntimeException {

   RangeException(){
      super();
   }

   RangeException(String message){
      super(message);
   }

}

这里只是我收到的一些输出,“超出范围”消息出现在多个位置,但是其余的似乎没问题。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

涉及到两个I / O流,一个用于标准输出(在您的示例中一个黑色打印),另一个用于标准错误(一个用于在您的示例中以红色打印)。这两个流之间没有排序保证。

相对于发送消息的线程,只有与发送到这些I / O流中的消息一起才有顺序保证(在您的情况下,因为您有一个单线程示例,这意味着可以保证相对于其他黑色消息,黑色消息显示顺序相同,相对于其他红色消息,红色消息显示顺序相同。

相关问题