Structs, enums y traits
Rust Error Handling: Result and ?
Errors are values in Rust. Return Result, handle it with match, and pass errors on with ?.
Lo que aprenderás
- 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.
Puntos clave
- Result<T, E> is
Ok(value)orErr(error). - ? returns the error to the caller at once.
- The caller decides what to do.
Ejemplo ejecutable 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")Practica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- Primera edad no válida Valida las edades escritas y señala dónde está la primera entrada incorrecta en lugar de dejar que el programa falle. Fácil
- Sumar los números válidos Suma las entradas que sean números enteros y omite todo lo demás, como maneja try/except la entrada incorrecta. Fácil