Eclipse中的控制台打印顺序

我在Eclipse中输入了一个简单的算术程序。 在Eclipse中运行程序时,每次运行时输出都会以奇怪的顺序出现。 有时,exception出现在最后的print语句中(这是正确的方法)。 有时它会在混乱的顺序中反过来。 为什么会发生这种情况以及如何纠正它? 是否有任何设置可以在每次执行时以正确的方式打印。 以下屏幕截图显示了它的显示方式。 请帮我纠正这个问题。

正确的顺序: 运行时更正订单

我们运行几次后错误的订单 订单不正确

package com; public class Abc { /** * @param args */ public static void main(String[] args) { System.out.println("begin main"); // TODO Auto-generated method stub int a = 10; int b = 0; int c = 0; System.out.println("value of a BD is " + a); System.out.println("value of b BD is " + b); System.out.println("value of c BD is " + c); c = a/b; //Arthmetic Exception System.out.println("value of a AD is " + a); System.out.println("value of b AD is " + b); System.out.println("value of c AD is " + c); } } 

更详细一点:print语句的输出转到System.out 。 但是,exception消息将发送到System.err (请参阅此内容 )。 这两个是分开的输出流,它们都碰巧到了同一个地方:你的控制台。 它们是独立缓冲和处理的。 在您显示的第二种情况中, print语句正在缓冲但在exception发生时尚未打印。

编辑这里有一个额外的复杂function,即Eclipse控制台不是真正的Windows控制台。 正如其他地方所述,过去在Windows平台上存在Eclipse控制台的问题,因为Windows并没有为Eclipse提供一种使其控制台像本机控制台一样运行的好方法。 如果添加flush调用但仍有问题,请尝试从命令提示符运行程序,看看是否有所不同。

这里使用了两种不同的流。 您正在使用System.out. 并使用System.err打印exception。 它们是缓冲的,因此一个输出可以在另一个之前打印。

你可以调用System.out.flush(); 在例外行之前:

 System.out.flush(); c = a/b; //Arthmetic Exception