3 ms·
The Rust docs specifically discourage using panics as try/catch: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html https://doc.rust-lang.org/std/panic/fn
by haberman 2y ago
The Rust docs specifically discourage using panics as try/catch: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
> It is not recommended to use this function for a general try/catch mechanism. The Result type is more appropriate to use for functions that can fail on a regular basis. Additionally, this function is not guaranteed to catch all panics, see the “Notes” section below.
I think panics in Rust are intended to be unrecoverable, and catch_unwind is mainly intended to make the shutdown more orderly and possibly localized. Any data structure that paniced is probably in an unknown state that is not safe for further use.
- brokencode 2y agoThe situation in Rust seems to be a bit complicated. But I did find that panicking within a thread you spawn kills just that thread and not the whole program. And it seems that Tokio has the same behavior. https://github.com/tokio-rs/tokio/issues/2002#issuecomment-663886031 https://github.com/tokio-rs/tokio/issues/2002#issuecomment-6... And web frameworks like Tower provide standard ways of handling panics and turning them into error responses. https://docs.rs/tower-http/latest/tower_http/catch_panic/index.html https://docs.rs/tower-http/latest/tower_http/catch_panic/ind... So I don’t think panics are necessarily meant to be program-killing in Rust, even if Result types are heavily recommended instead.
- Too 2y agohttps://doc.rust-lang.org/nomicon/unwinding.html https://doc.rust-lang.org/nomicon/unwinding.html explains the philosophy and how they got there a bit further. Rust grew from a short-lived task concept, where panic of a task wouldn't be the end of the world, then it got used to write bigger applications instead and finer catch-concepts were needed.
- J_Shelby_J 2y agoCatch unwind is useful when you have a dependency that for some reason panics and you can’t control it.