5 ms·
> 2. If you have an invariant that you either can't (or won't) move into the type system, then unwrap/expect/panic'ing can be appropriate precisely because if t
by p0nce 9y ago
> 2. If you have an invariant that you either can't (or won't) move into the type system, then unwrap/expect/panic'ing can be appropriate precisely because if that unwrap gets tripped, then that will indicate a bug in your program that should be fixed.
Absolutely but using the same mechanism (unwrap/panic) for both types of errors - recoverable and recoverable - can creates confusion.
panic'ing for wrong user input for example as can be seen in example code.
- kibwen 9y agopanics aren't for recoverable errors, in any circumstances. It is technically possible to "halt" the unwinding from a panic, but 1) that's intended for C interop, 2) the feature has been deliberately designed to make your life hell if you try to use it to emulate recoverable exceptions, and 3) Rust makes no guarantees that panics will unwind at all, it is entirely legal for a user to configure panics so that they all abort instead.
- p0nce 9y ago> panics aren't for recoverable errors, in any circumstances. And I understand that. Hence why unwrap everywhere is harmful.
- kibwen 9y agoEr, it was a response to this line of yours: > Absolutely but using the same mechanism (unwrap/panic) for both types of errors - recoverable and recoverable Nobody is using panics with the intent to recover, in the classic sense of "recoverable error".
- p0nce 9y agoSee above where one user is using .unwrap for parsing errors (input errors are recoverable).
- cyphar 9y agoNot in all cases. Most daemons will die if you give them an invalid configuration file (with a description of the syntax error).
- derefr 9y agoI think this discussion is muddying the meanings of "recoverable" between "recoverable as a class" and "recoverable in this instance." Parsing errors are recoverable as a class—you haven't irretrievably corrupted your process memory when you encounter one. Therefore, the parser itself should not panic(); it should just return an option type. Parsing errors may very well be unrecoverable in a particular instance. The code calling the parser has every right to decide to unwrap() the option type such that a panic() will happen if the parse failed. The code calling the parser is likely business-logic code of an application, and is privy to knowledge like "if there is no configuration supplied here, then later code that tries to consume the configuration will have to crash" and so can decide to early-exit with a user-comprehensible error ("you don't have a config file!") rather than letting the later code crash with some weird error about a config value being Nothing.
- p0nce 9y agoYes the problem is with the grey area between recoverable and unrecoverable. .unwrap is only suitable for the unrecoverable case, while exceptions are suitable for both cases. Hence why .unwrap in examples is harmful imho.