4 ms·
but it seems you can either use `Result` to handle errors (and force the caller to deal with it) or crash with `panic` To me, there is a large difference betwe
by danieldk 6y ago
but it seems you can either use `Result` to handle errors (and force the caller to deal with it) or crash with `panic`
To me, there is a large difference between them.
Result is for computations that can fail, such as opening a file or reading from a socket. Computations that fail should be handled by the caller (e.g. report a nice error which file could not be opened or attempting to open a new socket and retry the communication).
panic, in particular through assertions, are for catching programming errors, such as violation of invariants. These are cases where the program should just crash and burn, because it would be in an invalid state otherwise. E.g. splitting a Vec at an invalid index is a programming error. If a program attempts such a split, it is already in an invalid state, so it should crash and the bug should be fixed.
What I usually do in other languages is use exceptions as assertions, when it is just a simple one-off app, but then go back and catch the exceptions when possible to make it more user friendly and robust.
The Rust equivalent is letting Result::Err bubble up the call chain and have a
fn main() -> Result<(), Error>
or even nicer:
fn main() -> anyhow::Result<()>