I noticed that Rust does not have exceptions. How to do error handling in Rust and what are the common pitfalls? Are there ways to control flow with raise, catch, reraise and other stuff? I found inconsistent information on this.
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- How do I identify what code is generating “ '&
- Pattern matching on slices
- How can I iteratively call Sha256::digest, passing
相关文章
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- <link> onerror do not work in IE
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- Could not find default endpoint element that refer
- How to get struct field names in Rust? [duplicate]
- Confusion between [T] and &[T]
Rust generally solves errors in two ways:
Unrecoverable errors. Once you
panic!
, that's it. Your program or thread aborts because it encounters something it can't solve and its invariants have been violated. E.g. if you find invalid sequences in what should be a UTF-8 string.Recoverable errors. Also called failures in some documentation. Instead of panicking, you emit a
Option<T>
orResult<T, E>
. In these cases, you have a choice between a valid valueSome(T)
/Ok(T)
respectively or an invalid valueNone
/Error(E)
. GenerallyNone
serves as anull
replacement, showing that the value is missing.Now comes the hard part. Application.
Unwrap
Sometimes dealing with an
Option
is a pain in the neck, and you are almost guaranteed to get a value and not an error.In those cases it's perfectly fine to use
unwrap
.unwrap
turnsSome(e)
andOk(e)
intoe
, otherwise it panics. Unwrap is a tool to turn your recoverable errors into unrecoverable.Inside the
if
-block it's perfectly fine to unwrap since it should never panic because we've already checked that it isSome
withx.is_some()
.If you're writing a library, using
unwrap
is discouraged because when it panics the user cannot handle the error. Additionally, a future update may change the invariant. Imagine if the example above hadif x.is_some() || always_return_true()
. The invariant would changed, andunwrap
could panic.?
operator /try!
macroWhat's the
?
operator or thetry!
macro? A short explanation is that it either returns the value inside anOk()
or prematurely returns error.Here is a simplified definition of what the operator or macro expand to:
If you use it like this:
It will convert it into this:
The downside is that your functions now return
Result
.Combinators
Option
andResult
have some convenience methods that allow chaining and dealing with errors in an understandable manner. Methods likeand
,and_then
,or
,or_else
,ok_or
,map_err
, etc.For example, you could have a default value in case your value is botched.
Or if you want to turn your
Option
into aResult
.This is just a brief skim of things you can do. For more explanation, check out: