Detect if rust is unwinding

Is there a way to determine if rust is currently unwinding the stack after a panic? My use case is that I have a type that needs to call a tear down function that is fallible (returns result), so I can’t call it in drop. I would like to check in the drop function that the tear down happened, but what do I do if it didn’t happen? Panicking would be fine, expect that if we are currently panicking when drop gets called then it will cause problems with the unwinding stack and backtrace. I would like to detect if we are unwinding, and only if we are not do the tear down check which could panic in drop.

You'll want to pay attention to RFC 3288 on that front.

See std::thread::panicking.

1 Like

Here you go, this function takes a closure and returns a result. The result will be Ok if the closure didn't panic, or Err if it did

Please don't panic in a destructor. People won't be happy when code they don't explicitly write or opt into panics.

Instead, I would design my API so any errors cleaning up the resource in the destructor are logged or simply ignored, and if people want to explicitly handle the errors then give them an explicit fn cleanup(self) -> Result<(), Error> method.

Similar to what std::fs::File does.

2 Likes