Java Exceptions

There is a lot that can be said on this subject however I am going to cover a common and simple scenario. If your code is running in a JVM container or some other kind of virtualisation container you may not see the standard output and so you need to put things into log files. Starting with exception handling code like this:

        catch (Exception ex) {
            ex.printStackTrace();
        }

You can convert it to output to a String by doing the following:

        catch (Exception ex) {
            StringWriter error = new StringWriter();
            ex.printStackTrace(new PrintWriter(error));
            System.out.println("The stack trace....." + System.lineSeparator() + error.toString());
        }

Which is simple, once you know how.