3 ms·
I remember my disappointment when I found out panics could be “caught” and that I was still living in the world of exceptions
by robinsonrc 3y ago
I remember my disappointment when I found out panics could be “caught” and that I was still living in the world of exceptions
- josephg 3y agoOh no, I didn't know this. I'm adding panic = "abort" to all my projects. If I wanted exceptions I wouldn't be using rust.
- lifthrasiir 3y agoThat's actually not too bad if you know you don't need to recover from panic. I kinda hope that `panic = "abort"` is indeed default unless overridden by dependencies, say, tokio...
- formerly_proven 3y agoYou can catch them locally (https://doc.rust-lang.org/std/panic/fn.catch_unwind.html https://doc.rust-lang.org/std/panic/fn.catch_unwind.html) or with a global exception handler (https://doc.rust-lang.org/std/panic/fn.set_hook.html https://doc.rust-lang.org/std/panic/fn.set_hook.html)
- kibwen 3y agoPanics have to be catchable because it's undefined behavior for Rust to unwind through C code, so a Rust library that exposes a C API has to stop panics at the FFI boundary and propagate errors in a C-compatible way. It's not "catching" in the Java sense; nobody is using catch_panic to implement resumable error-handling.
- IshKebab 3y agoYou aren't. They're only caught in special cases, e.g. if a thread panics and you want to propagate that to other threads, to catch panics in unit tests, to avoid unwinding across FFI, etc. You shouldn't use them as a general exception mechanism. They aren't the same, even if under the hood they both use stack unwinding.
- vacuity 3y agoNaively, what is the difference between panics and exceptions? Is it the philosophy on when/how to use them?
- IshKebab 3y agoYes, and also exceptions can have arbitrary value associated with them. You aren't going to get far using panics as a general error handling mechanism because there's only one type of panic.