this post was submitted on 18 Dec 2025
257 points (98.9% liked)
Programmer Humor
39521 readers
491 users here now
Post funny things about programming here! (Or just rant about your favourite programming language.)
Rules:
- Posts must be relevant to programming, programmers, or computer science.
- No NSFW content.
- Jokes must be in good taste. No hate speech, bigotry, etc.
founded 6 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
so you have to wrap everything in a try/catch?
It's worse than that. In C++, if you fail to catch an exception, then std::terminate() is called. In Rust the only options are roughly equivalent to C++ noexcept, or std::terminate() [panic in Rust]. There's nothing in between.
Rust does not have exceptions. You never have to try/catch. Functions usually encode the possible failures in their types, so you'd have something like this C++ snippet:
And then the caller of
downloadFilehas to decide what to do if it returns an error:However, Rust makes this whole thing a lot easier, by providing syntax sugar, and there are helper libraries that reduce the boilerplate. You usually end up with something like
(notice the
#[from], which forwards the error message etc from thestd::io::Errortype)The
Resulttype is kind of like astd::variantwith two template arguments, and, mostly by convention, the first one denotes the successful execution, while the second one is the error type.Resulthas a bunch of methods defined on it that help you with error handling.Consumer code is something like this:
Or
Which will just forward the error to your caller (but your function has to return
Resultas well), or proceed with the execution if the function succeeded.Finally,
download_file(url).unwrap()is if you can neither ignore, nor handle, nor pass the error to the caller. It will abort if the function fails in any way, and there's no (practical) way to catch that abort.Not really, because rust doesn't have exceptions. Instead you are encouraged to handle every possible case with pattern matching. For example:
Option is a type which can either be some 8bit unsigned integer, or none. It's conceptually similar to a
Nullable<int>in C#.In C# you could correctly implement this like:
In rust, you can call Unwrap on an option to get the underlying value, but it will panic if the value is None (because None isn't a u8):
In some cases unwrap could be useful if you don't care about a panic or if you know the value can't be
None. Sometimes it's just used as a shortcut. You can likewise do this in C#:But this throws an exception if number is null.
A panic isn't the same as an exception though, you can't 'catch' a panic, it's unrecoverable and the program will terminate more-or-less immediately.
Rust provides a generic type
Result<T, E>, T being a successful result and E being some error type, which you are encouraged to use along with pattern matching to make sure all cases are handled.