Wednesday, September 5, 2012

Stack Overflow


Some exercises. Exercise 1. What is wrong with this piece of code: 
try {    runSubs(objectFieldValue);
} catch (java.lang.StackOverflowError e) {
   System.out.println("[StackOverflowError] objectFieldValue: " + objectFieldValue);
   throw e;
}
Answer: the println() will of course overflow the stack too. (EDIT: seems it was the code I was debugging that caused this; i.e. the toString() contained some circularity. I wrote some simple code where a similar print statement seems to _not_ overflow. Although it should, the '+' gets compiled to a call to a string concatenation/append, doesn't it?)

What is wrong with instead doing just:
try {   runSubs(objectFieldValue);catch (java.lang.StackOverflowError e) {
   throw e;
}
...and setting a breakpoint at 'throw e'?

Answer: Well, nothing wrong per se; but you won't be able to see anything in the (Eclipse) debugger: it simply can't handle those stack depths. Maybe if you set a small stack allocation, but then you may get false positives.

So. If you didn't know it before, debugging StackOverflowError is a pain.

One might of course use some flags or counters or stuff, and handle the stack overflow further out. Cumbersome.

If you've got any good ideas or solutions, please don't hesitate to comment.


No comments:

Post a Comment