Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get stack trace of an exception in Scala to print it?

In a program of mine I'd like to catch all exceptions and explicitly print them (to be able to proceed with finally while still seeing exceptions).

So I've tried this:


try {
  ...
}
catch {
  case ex : Exception => {
    println ("\n" + ex)
    println ("\n" + ex.getStackTrace + "\n")
  }
}
finally {
  ...
}

But this (using getStackTrace) itself causes "java.lang.OutOfMemoryError: PermGen space". What am I doing wrong? I am sure I have plenty of free JVM heap memory free before getting this (as I've tried causing an exception in the very beginning of the program).

like image 461
Ivan Avatar asked Oct 24 '10 22:10

Ivan


People also ask

How do I print an exception stack trace?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

How do I print a string stack trace?

Example: Convert stack trace to a stringIn the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer. Then, we simply convert it to string using toString() method.

How do I read stack trace errors?

The stack trace first prints the function call that caused the error and then prints the previous underlying calls that led up to the faulty call. Therefore, reading the first line of the stack trace shows you the exact function call that threw an error.


1 Answers

I think you should post an exact, standalone working example of this because this works for me using 2.8.0 (i.e. exhibits no memory problems at all):

scala> def foo( f : () => Unit) : Unit = try {
     | f()
     | } catch { case e : Exception => println("H" + e.getStackTrace) }
foo: (f: () => Unit)Unit

scala> foo(() => throw new NullPointerException)
H[Ljava.lang.StackTraceElement;@30a4effe

I wonder whether you have an exception which is its own cause? Conversely it may be the case that your program is running very low on memory (32Mb is the default on a client-class machine by the way) and you have a very deep stack (not uncommon in scala-land!)

like image 193
oxbow_lakes Avatar answered Oct 20 '22 03:10

oxbow_lakes