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).
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.
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.
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.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With