I prefer it over alternatives:
- Exceptions: ”Oh no! Guess I’ll just die”
- Error codes: ”If a non-zero error code is returned but no one notices, is it really an error?”
I prefer it over alternatives:
Sad to be the one that does not get it.
Unwrap means it forces to evaluate the result as an ”ok value”. If it’s an ”error value”, it will crash. It’s a bad practice to rely on it, as it’s one of the most common ways a Rust programs can crash.
Rust offers many options to handle errors that don’t risk crashing. For example, unwrap_or_default, which means ”if it’s an error value, use the default value for this type, such as 0 for integers”
I mean using unwrap is not bad practice if the value is guaranteed to not be none, which can happen frequently in some applications.
A good example would be regex. After validating it when writing the program it should always compile, although this could also be solved with a proc macro that validates the regex at compile time.
It's guaranteed to not be None, why is it an Option?
Here's a bad example but hopefully captures the why. https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=43d055381e7bb52569c339d4526818f4
We have a condition we know must be satisfied (the option will always be Some), but cant prove in code.
Oh, it can happen when you do calculations with compile-time constants...
But the GP's claim that it's a "frequent" thing is suspect.
(Crashing is also useful when you are writing and-user applications, but you'll probably want .expect like in the meme.)
A very typical use-case would be getting something from a HashMap (or a Vector) and calling unwrap because you know it must exist (as you got a reference to the index or object that must be valid in the HashMap or Vector).
Or if you call a function that returns Option<…> depending on the current state and you know that it must return Some(…) in the current situation.
Unwrap is good for prototyping and trying out stuff fast, but it generally shouldn't make it past a code review onto main, unless you're very sure
try
{
execute.SomeMethod();
}
catch(Exception ex)
{}
I've seen this in production code before. I might argue if you caught a very specific exception type that didn't matter it might be acceptable. Maybe. But just the overall Exception type... Recipe for disaster.
What really sucks, imho, is that lazy programmers won in java's checked exception wars.
With checked exceptions you have to type a little more, but it means that you can be sure you caught every exception type.
By making everything into a runtime exception you never know if you caught all relevant types of exceptions.
Which then again leads to people blanket-catching Exception because that way the app will at least not randomly crash due to a forgotten catch for some obscure exception type.
It's a trash solution for a trash problem caused by lazyness even though there was a real solution available all along.
all 22 comments