Structs, enums e traits
Rust Error Handling: Result and ?
Errors are values in Rust. Return Result, handle it with match, and pass errors on with ?.
O que você vai aprender
- Ok and Err
- The ? operator
- Your own error messages
parse_and_double("abc")
- 1
text.parse()fails - 2
?returns early - 3
Err(...)the caller gets the error
Success or error, as a value
Rust has no exceptions. A function that can fail returns Result<T, E>, which is either Ok(value) or Err(error). The caller decides what to do with the error.
The ? after parse returns the error to the caller at once when parsing fails; otherwise it gives the number. divide uses a String as its error type and returns Err for a zero divisor. match prints the value or the error message.
Pontos-chave
- Result<T, E> is
Ok(value)orErr(error). - ? returns the error to the caller at once.
- The caller decides what to do.
Exemplo executável de Rust
main.rs
use std::num::ParseIntError;
fn parse_and_double(text: &str) -> Result<i32, ParseIntError> {
let number: i32 = text.trim().parse()?; // ? returns the error early
Ok(number * 2)
}
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err(String::from("cannot divide by zero"));
}
Ok(a / b)
}
fn main() {
for input in ["21", "abc"] {
match parse_and_double(input) {
Ok(value) => println!("{input} -> {value}"),
Err(error) => println!("{input} -> error: {error}"),
}
}
println!("{:?}", divide(10, 2));
println!("{:?}", divide(1, 0));
}
21 -> 42
abc -> error: invalid digit found in string
Ok(5)
Err("cannot divide by zero")Pratique
Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.
Terminou esta lição?
Marque como aprendida para acompanhar seu progresso.
Seu progresso está salvo neste navegador Entre para mantê-lo em todos os dispositivos.
Pratique com um desafio
Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.
- Primeira idade inválida Valide idades digitadas e informe onde está a primeira entrada inválida, em vez de deixar o programa quebrar. Fácil
- Somar os números válidos Some as entradas que são números inteiros e ignore todo o resto, do jeito que try/except lida com entrada inválida. Fácil