std::try - Rust
Description: API documentation for the Rust `try` macro in crate `std`.
Keywords: rust, rustlang, rust-lang, try

# Macro std::try [−]

    macro_rules! try {
        ( $ expr : expr ) => { ... };
    }

Helper macro for reducing boilerplate code for matching `Result` together with converting downstream errors.

Prefer using `?` syntax to `try!`. `?` is built in to the language and is more succinct than `try!`. It is the standard method for error propagation.

`try!` matches the given `Result`. In case of the `Ok` variant, the expression has the value of the wrapped value.

In case of the `Err` variant, it retrieves the inner error. `try!` then performs conversion using `From`. This provides automatic conversion between specialized errors and more general ones. The resulting error is then immediately returned.

Because of the early return, `try!` can only be used in functions that return `Result`.

# Examples

    use std::io;
    use std::fs::File;
    use std::io::prelude::*;

    enum MyError {
        FileWriteError
    }

    impl From<io::Error> for MyError {
        fn from(e: io::Error) -> MyError {
            MyError::FileWriteError
        }
    }

    fn write_to_file_using_try() -> Result<(), MyError> {
        let mut file = try!(File::create("my_best_friends.txt"));
        try!(file.write_all(b"This is a list of my best friends."));
        println!("I wrote to the file");
        Ok(())
    }
    // This is equivalent to:
    fn write_to_file_using_match() -> Result<(), MyError> {
        let mut file = try!(File::create("my_best_friends.txt"));
        match file.write_all(b"This is a list of my best friends.") {
            Ok(v) => v,
            Err(e) => return Err(From::from(e)),
        }
        println!("I wrote to the file");
        Ok(())
    }Run

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)