-2
try
{
    try
    {
        function(a, b);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        throw e;
    }
}
catch (Exception e)
{
    System.out.println("---------------------------------");
}

我做这个嵌套的 try-catch 块是有原因的,这就是当我尝试这个时

try
{
    function(a, b);
}
catch (Exception e)
{
    e.printStackTrace();
    System.out.println("---------------------------------");
}

我打印的行大部分时间都在堆栈跟踪的中间..

我的问题是为什么大多数时候会发生这种情况?有没有更干净的方法来避免这个问题?

4

3 回答 3

4

The problem is that the stack trace is written to the standard error stream, whereas your line is written to the standard output stream. Replace it by

e.printStackTrace();
System.err.println("---------------------------------");

or to

e.printStackTrace(System.out);
System.out.println("---------------------------------");

In an enterprise application even more than in a client application, you should not print to the standard streams anyway. Use a real logging framework like slf4j, which will allow you to choose levels of logging, destinations, etc.

于 2013-12-16T07:28:19.970 回答
1

As Throwable.printStackTrace() and System.out.println(Object) write to different consoles (stderr and stdout), they might not be synchronized.

1st proposal: write the error to the stdout:

e.printStackTrace(System.out);

or 2nd proposal: explicitly flush the stderr buffer (and use it like in your second variant):

e.printStackTrace();
System.err.flush();
System.out.println(...);
于 2013-12-16T07:31:13.067 回答
1

It looks like the "--------" comes inbetween the printed stack trace because the exception is printed on System.err while the "------" is printed on the System.out, but both print to the console.

So this can happen:

  1. e.printStackTrace() prints everything to System.err, but not all is immediatly flushed to the console.
  2. System.out.println("--------------") prints the "----" to System.out and immediatly flushes it.
  3. the rest of the System.err is now flushed

Flush the error stream before using System.out if you want System.err and System.out to appear in sequence in the console.

e.printStackTrace();
System.err.flush();
System.out.println("---------------------------------");

or use the error stream for both

e.printStackTrace();
System.err.println("---------------------------------");
于 2013-12-16T07:32:14.663 回答