In Rust, what happens when a Drop implementation panics while the thread is already unwinding from an earlier panic?
answer
- two panics at once
- cleanup code cannot unwind
- panic in a destructor during cleanup
- thread::panicking() as a guard
- an explicit close returning Result
basics
~20 sThe process aborts. A destructor panicking during unwinding would need a second unwind mid-cleanup, so the runtime prints 'panic in a destructor during cleanup' and aborts, past any catch_unwind. A Drop panic outside unwinding is an ordinary, catchable panic.
solid answer
~40 sUnwinding calls `Drop` on every live value; if one of those `drop` calls panics, a second unwind would have to start while the first is still in progress, and Rust does not support that. The cleanup path that called the destructor is not allowed to unwind, so the runtime prints the second panic's message (the default hook forces a full backtrace for it), then `panic in a destructor during cleanup` and `thread caused non-unwinding panic. aborting.`, and aborts, even inside `catch_unwind`. The same `drop` panicking during a normal scope exit is just a regular panic. So destructors should avoid panicking: check `std::thread::panicking()` if a destructor must choose, and better, give the type an explicit `close` or `flush` method that returns a `Result`, as `std::io::BufWriter` does; its `Drop` ignores a failed flush.
code
rust · 15 linesstruct Flush;
impl Drop for Flush {
fn drop(&mut self) {
// simulate a failing flush that panics
panic!("flush failed");
}
}
fn main() {
let r = std::panic::catch_unwind(|| {
let _f = Flush;
panic!("request {} failed", 42);
});
println!("never printed: {}", r.is_err());
}go deeper
Remember that destructors run while a panic unwinds, and that a destructor which panics during that clean-up crashes the whole program.
Explain why a second panic during unwinding aborts, how that differs from a Drop panic during a normal scope exit, and what std::thread::panicking() reports.
Diagnose the two-message abort from logs, find the destructor that panicked, and harden guard types with best-effort Drop plus an explicit fallible close.
Set the expectation that destructors in shared crates never panic and that fallible clean-up is exposed as a Result-returning method reviewers can check.
## The double panic During unwinding, the runtime drops every live value in every frame it leaves. A **double panic** is what happens when one of those `drop` calls panics too. In a request handler that looks like this: 1. The handler panics, say on a failed `unwrap`, and the panic hook prints the first message. 2. Unwinding begins and reaches a local whose `Drop` flushes a buffer. 3. The flush fails and that `drop` calls `panic!`. 4. The default hook prints the second message and, because this thread is now panicking twice, forces a **full stack backtrace** whatever `RUST_BACKTRACE` says. 5. The second panic tries to leave the destructor, but the cleanup code that called it is not allowed to unwind. The runtime prints `panic in a destructor during cleanup`, then `thread caused non-unwinding panic. aborting.`, and **aborts the process**. A `catch_unwind` around the handler does not help: an abort never returns to it. ## Why the runtime aborts Unwinding is a single walk up the stack, cleaning as it goes. A second panic in the middle would need a second walk to start inside the first, with two payloads and two sets of half-run clean-up. Rust does not try to merge or pick between them. The compiler generates the clean-up paths that run destructors during unwinding as code that must not unwind, and when something unwinds out of one, codegen routes it to a runtime routine whose whole message is `panic in a destructor during cleanup`. The same reasoning covers a panic **inside the panic hook**, which aborts with `thread panicked while processing panic. aborting.` ## A Drop panic outside unwinding If no panic is in progress, a destructor that panics starts an **ordinary** panic. It unwinds from inside `drop`, the remaining locals are dropped, and `catch_unwind` or a thread's `join` reports it like any other panic. "Any panic in `Drop` aborts" is therefore wrong; the abort needs a panic that is *already unwinding*. | Situation | Result | |---|---| | `drop` panics during a normal scope exit | ordinary panic, catchable | | `drop` panics while an earlier panic unwinds | abort: `panic in a destructor during cleanup` | | the panic hook panics | abort: `thread panicked while processing panic. aborting.` | | dropping the payload after `main` panicked panics | std aborts: `drop of the panic payload panicked` | ## Defending against it The rule follows from the table: **a destructor should not panic**, because it cannot know which row it is in unless it asks. - **Ask.** `std::thread::panicking()` returns `true` while the current thread is unwinding. A destructor can skip work that might panic, or just log, when it is already in a panic. - **Swallow, then offer an explicit path.** `std::io::BufWriter`'s `Drop` flushes and, per the comment in its source, ignores a failed flush because destructors should not panic. To *see* that error you call `flush()` or `into_inner()` yourself, which return a `Result`. Your own guard types can follow the same shape: a `close(self) -> Result<(), E>` method for callers who care, and a best-effort `Drop` for everyone else. - **Audit what `drop` calls.** `unwrap`, `expect`, slice indexing, a `RefCell::borrow_mut` that may already be borrowed: each is a panic waiting for the worst moment. - **Keep hooks just as careful**, since a hook that panics also aborts. ## How it shows up in production The symptom is a process that dies with `SIGABRT` (status 134 in a Unix shell) instead of exiting with 101 or surviving through `catch_unwind`, and stderr shows two panic messages back to back, the second followed by a full backtrace and `panic in a destructor during cleanup`. Read the **first** message for the original bug and the **second** for the destructor to harden. Both are real defects: the first started the panic, the second turned a recoverable failure into a process crash. The abort itself cannot be tested in-process, but the guard can: a unit test that panics inside `catch_unwind` while the guard is alive, then asserts that `catch_unwind` returned `Err`, proves the destructor took its `std::thread::panicking()` path instead of panicking again. If the destructor regresses, the test binary aborts, which the test runner reports as a crash rather than a quiet pass.
- How can a Rust Drop impl tell that it is running because the thread is unwinding?Call `std::thread::panicking()`. It returns `true` while the current thread is unwinding from a panic, so a destructor can skip fallible work, or log instead of panicking, and avoid turning the panic into an abort.
- Why does std::io::BufWriter not report a failed flush from its Drop impl?A destructor cannot return a `Result`, and panicking there risks a double-panic abort, so its `Drop` makes a best-effort flush and ignores the error. Code that must know the data reached the writer calls `flush()` or `into_inner()` first; both return a `Result`.
- catch_unwind catches a destructor's panic along with the original one.
- The second panic replaces the first and unwinding carries on.
- Any panic in a Drop impl aborts, even with no panic in progress.
- Drop cannot return a Result, so panicking is how it reports errors.