2

What is the most efficient method to convert an throwable/exception's entire stack trace into a ByteBuffer (in Java)?

Specifically, I need to log the entire exception into the database. The Thread.currentThread().getStackTrace() returns a list of StackTraceElement[] array.

Then, there is a printStackTrace() method in Throwable class?

Michael Easter
  • 23,733
  • 7
  • 76
  • 107
ikevin8me
  • 4,253
  • 5
  • 44
  • 84
  • 1
    You just *don't* use exception-throwing code where performance is significant. Getting and formatting the stack trace is not very efficient anyway. – gpeche Sep 19 '12 at 16:36
  • 1
    @gpeche - I don't think avoiding Exceptions altogether is a good suggestion. It may not even be an option if dealing with third-party libs. Even if your code is slow and performance is a concern, there are probably a million other things to profile and optimize first before considering to stop using Exceptions. They may be slow but not _that_ slow. – Jesse Webb Sep 19 '12 at 16:50
  • 1
    @Jesse Webb In fact I prefer exception handling to the alternatives, it's just that "the most efficient method to convert an throwable/exception's entire stack trace into a ByteBuffer" does not make much sense to me. A bit like asking about the most efficient method to write to `System.out`. – gpeche Sep 19 '12 at 18:05

2 Answers2

6

If you really want to do that, this should be what you need:

ByteArrayOutputStream os = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(os));
ByteBuffer bb = ByteBuffer.wrap(os.toByteArray());
assylias
  • 321,522
  • 82
  • 660
  • 783
1

You can use ExceptionUtils class in apache commons.

Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
basiljames
  • 4,777
  • 4
  • 24
  • 41
  • Specifically, the `getFullStackTrace()` method should be used. It includes the stack of any nested Exceptions while the `getStackTrace()` method does not. It returns a String, which can easily be turned into bytes. http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/exception/ExceptionUtils.html#getFullStackTrace%28java.lang.Throwable%29 – Jesse Webb Sep 19 '12 at 16:47