Skip to content

Commit

Permalink
remove example usage of from_str in error docs
Browse files Browse the repository at this point in the history
Fixes #24185
  • Loading branch information
steveklabnik committed Apr 16, 2015
1 parent 5576b05 commit e6f1a4d
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions src/doc/trpl/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,18 @@ panic. A *failure* is an error that can be recovered from in some way. A
*panic* is an error that cannot be recovered from.

What do we mean by "recover"? Well, in most cases, the possibility of an error
is expected. For example, consider the `from_str` function:
is expected. For example, consider the `parse` function:

```{rust,ignore}
from_str("5");
```ignore
"5".parse();
```

This function takes a string argument and converts it into another type. But
because it's a string, you can't be sure that the conversion actually works.
For example, what should this convert to?
This method converts a string into another type. But because it's a string, you
can't be sure that the conversion actually works. For example, what should this
convert to?

```{rust,ignore}
from_str("hello5world");
```ignore
"hello5world".parse();
```

This won't work. So we know that this function will only work properly for some
Expand All @@ -40,7 +40,8 @@ inputs. It's expected behavior. We call this kind of error a *failure*.
On the other hand, sometimes, there are errors that are unexpected, or which
we cannot recover from. A classic example is an `assert!`:

```{rust,ignore}
```rust
# let x = 5;
assert!(x == 5);
```

Expand Down Expand Up @@ -119,17 +120,19 @@ Rust calls these sorts of errors *panics*.
# Handling errors with `Option` and `Result`

The simplest way to indicate that a function may fail is to use the `Option<T>`
type. Remember our `from_str()` example? Here's its type signature:
type. For example, the `find` method on strings attempts to find a pattern
in a string, and returns an `Option`:

```{rust,ignore}
pub fn from_str<A: FromStr>(s: &str) -> Option<A>
```rust
let s = "foo";

assert_eq!(s.find('f'), Some(0));
assert_eq!(s.find('z'), None);
```

`from_str()` returns an `Option<A>`. If the conversion succeeds, it will return
`Some(value)`, and if it fails, it will return `None`.

This is appropriate for the simplest of cases, but doesn't give us a lot of
information in the failure case. What if we wanted to know _why_ the conversion
information in the failure case. What if we wanted to know _why_ the function
failed? For this, we can use the `Result<T, E>` type. It looks like this:

```rust
Expand Down

0 comments on commit e6f1a4d

Please sign in to comment.