Search code examples
javaexceptiontry-catchcatch-block

Is there a cleaner way to do this in Java try-catch?


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 ?


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.