Catching a stack overflow

Hi all, long time no see!

In my Rusty quests I have come across a problem. I have a lovely recursive function, which stack overflows from time to time when the graph I am consuming has too many nodes. I think it's good that this function does fail when it does - that's not really an issue. What I would like is to be able to catch this stack overflow and call a different function when it does overflow. Is there a nice way of doing this?

I came across this:

But it didn't solve the problem, a commenter in this post said that catch_unwind() did not help.

Many thanks in advance for any help!

Use a counter to keep track of the recursion depth, and stop when it gets too deep.
Catching a stack overflow is something you shouldn't find yourself doing in Rust unless you know exactly what you're doing.

Thanks for this - do you have a quick example of how this would be done?

You could convert the following recursive function fn rec(.....) {} to

const DEPTH_LIM: i64 = ...;  // Pick your depth limit
fn rec(..., depth: i64) {
      if (depth > DEPTH_LIM) {
             // Handle the case of depth limit exceeded
            eprintln!("Depth limit exceeded!");
      // Rest of the logic
      // Now recurse
      rec(..., depth + 1);
      // You can have more logic here
1 Like

Brilliant, thank youuu!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.