Question

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

I do this nested try-catch block for a reason, which is simply that when I try this

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

The line I print comes in the middle of the stack-trace most the time..

My question is why does that happen most the time ? and is there a cleaner way to avoid that issue ?

Was it helpful?

Solution

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.

OTHER TIPS

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(...);

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("---------------------------------");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top