Search code examples
memory-managementrustdestructorexception-safety

Why do destructors run when a panic occurs?


If a Rust program panics, and assuming there are no panic catchers (which for a while there wasn't), surely it would be safe and fine to not run destructors and just let the OS clean up after the process. Why does Rust unwind the thread?

The only reason I can think of is for when there isn't an OS to reclaim the memory, but apart from that niche, it seems unnecessary.


Solution

  • There is a faulty premise in your question: it pre-supposes that the only reason to use a destructor is to clean-up resources of the current process.

    This is, indeed, the most common usage, but it is not the only one.

    For example, I could perfectly imagine that the destructor of a TCP connection would attempt to send a close message: the soonest the connection is closed, the soonest resources are released on the other end. Of course, it's only a best effort (in case of abort/crash the destructor is never run), but it can still be worthwhile.