How to get stack trace of an exception in Scala to print it?
In开发者_如何学C 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).
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!)
Sounds like you need to allocate more permgen space. In Java you do this with a JVM argument:
-XX:MaxPermGen=256m
You can set JVM args to be used by Scala by setting an environment variable:
JAVA_OPTS="-XX:MaxPermGen=256m"
精彩评论