【问题标题】:I'm getting irregular output for this program? Why?我得到这个程序的不规则输出?为什么?
【发布时间】:2016-02-22 07:03:09
【问题描述】:

最后一个例子

public class FinallyExample {

    public static void main(String[] args) {
        new FinallyExample().dothework();
    }
    public void dothework()
        {
            Object o=null;
            for(int i=0;i<=4;i++)
            {
                System.out.println(" "+i);
        try{ o=makeObj(i);}catch(IllegalArgumentException e){System.err.println("Error: ("+e.getMessage()+").");}
            finally{System.err.println("All done");
            /*if(o==null)
            {
                System.exit(0);
            }*/
            }
            System.out.println(o);
        }
        }
    public Object makeObj(int type) throws IllegalArgumentException
    {
        if(type==1) throw new IllegalArgumentException ("Don't like type"+type);
        return null;
        }
}

输出的顺序总是不同的!

我正在使用eclipse。

O/P- 全部做完 错误:(不喜欢 type1)。 0 //当 i=1 时打印该行 空值 1

全部完成 空值 2 全部做完 空值 3 全部做完 空值 4 全部做完 空

O/P- 0 全部完成null 1

错误:(不喜欢 type1)。 全部做完 空值 2 全部做完 空值 3 全部做完 空值 4 全部做完 空

【问题讨论】:

  • 程序中只有一个线程在工作!
  • 在 Stack Overflow 上发布时,请统一格式化您的代码。现在到处都是。同时显示输出示例。
  • 问题可能与std-out和std-err被缓存/刷新的方式有关

标签: java methods try-catch-finally finally


【解决方案1】:

基本上,您正在写信给System.outSystem.err。目前尚不清楚(和特定于实现的)这些将缓冲多少数据,或者何时刷新它们,但您不必期望每次都保持一致。

我希望在写信给System.out 之后调用System.out.flush(),在写给System.err 之后调用System.err.flush() 会解决这个问题——但至少在Eclipse 中,它似乎没有。 (即使没有刷新,在 Windows 命令提示符下运行相同的代码每次都会给出相同的输出。)

基本上,这似乎是 Eclipse 控制台实现的产物。我不会担心它——当你试图诊断的时候要注意它。 (如果您将所有诊断输出发送到同一流,则不会有问题。)

【讨论】:

  • if(type==1) 条件变为真后 o/p 1
    错误:(不喜欢 type1)。
    全部完成
    有时我得到 o/p 1
    错误:(不喜欢 type1)。为什么全部完成?
  • @KushalMaharana:你的问题真的只是关于为什么在“错误:(不喜欢 type1)”之前打印“全部完成”,与其余的输出?真的不清楚确切地你在问什么。
  • 非常感谢乔恩·斯蒂克!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 2019-01-25
  • 1970-01-01
  • 2020-08-30
  • 2019-05-09
  • 2011-07-10
相关资源
最近更新 更多