On this page
try!
Prev: macro_rules | Up: builtins | Next: std
Rel: Result & ? operator, builtins, Ownership, Borrowing & Lifetimes
Ref: Rust Docs — try!
Tags: #public #prog #rust #builtins #tier/legacy
Availability
Built-in / Prelude (Pre-2018 Macro) — available with zero use imports.
Syntax & Overview
try!(expr)
Legacy Rust 1.0 error-propagation macro superseded by the built-in ? operator.
Legacy / Avoid: Prefer Result & ? operator in all modern Rust.
Notes & Pitfalls
- Early-return propagation operator (
?): UnwrapsOk(v)/Some(v)or returnsErr(e.into())/Noneimmediately (replacing the legacytry!()macro). - Works in
main() -> Result<(), Box<dyn std::error::Error>>: Keeps CLI entry points concise and idiomatic.
Example
fn sum_two(a: &str, b: &str) -> Result<i32, std::num::ParseIntError> {
let x: i32 = a.parse()?;
let y: i32 = b.parse()?;
Ok(x + y)
}
fn main() {
assert_eq!(sum_two("10", "32"), Ok(42));
assert!(sum_two("10", "bad").is_err());
}
Linked from
Related notes
- tuts/rust/builtins/macro_rules Linked here; links to this page; shared tags: #builtins, #prog, #rust, #tier
- tuts/rust/builtins Linked here; links to this page; shared tags: #builtins, #prog, #rust
- tuts/rust/builtins/Result Linked here; shared tags: #builtins, #prog, #rust, #tier
- tuts/rust/ownership_and_internals/ownership_borrowing_and_lifetimes Linked here; shared tags: #prog, #rust
- tuts/rust/std Linked here; shared tags: #prog, #rust
- tuts/rust/builtins/Clone shared tags: #builtins, #prog, #rust, #tier
- tuts/rust/builtins/Copy shared tags: #builtins, #prog, #rust, #tier
- tuts/rust/builtins/Drop shared tags: #builtins, #prog, #rust, #tier
- tuts/rust/builtins/From shared tags: #builtins, #prog, #rust, #tier
- tuts/rust/builtins/Iterator shared tags: #builtins, #prog, #rust, #tier