code: public static String getStackTrace(Throwable ex) {
          // Wrap a ByteArrayOutputStream with a PrintStream and write the stack trace to
          // the PrintStream.
          ByteArrayOutputStream outStream = new ByteArrayOutputStream();
          PrintStream prnStrm = new PrintStream(outStream);
          ex.printStackTrace(prnStrm);
          prnStrm.close();    // flushes content to the byte stream
  
          // Extract the byte stream as a single string.
          return outStream.toString();
      }
docs: Get the stack trace from the given exception or error as a string. By default,
  Throwable objects only allow accessing the stack trace as an StackTraceElement[]
  or via a PrintStream or PrintWriter.
  
  @param   ex  Exception, Error, or other object that implements Throwable.
  @return      The exception's stack trace as a string (with embedded newlines).