Rust does not have exceptions. Instead, it uses:
Result<T, E>type for recoverable errors
panic!macro for unrecoverable errors
We can call
panic! when there is no way out of the problem.
It terminates the program.
By default, when panic occurs we’ll only see the line in our code that led to
the panic. We can see the whole callstack by setting the
variable to anything other than
Our functins might return
Result if there is a chance of failure.
It’s brough in by the prelude.
An example of a built-in API that uses
In this case we’re
pacic!ing when error occurs.
Methods on Result
Result has some helper methods:
unwrap- returns value inside of
panic!s if there’s error. It’s a shortcut which can be used instead of
unwrap, but allows to specify error message for the potential panic.
unwrap_or_else- returns value inside of
Okor executes a lambda passed to it in the case of
The ? Operator
? placed after a
Result value works as follows:
- if it’s
- if there’s an error, the containing function returns that error
? can convert the error to the expected
Error type that a function
normally would return (the
From trait needs to be implemented).
In the case above,
? does not need to convert the error since all the expected
errors would be of type
io:Error - the same type that the function returns.