El manejo de excepciones nos ayuda a que nuestros programas continuen su flujo a pesar de algún error o fallo existente.
Rust posee mecanismos para el manejo de excepciones de una manera similar a lo que se hace en lenguajes como Java, C#, Python entre otros más.
Ejemplos de manejo de excepciones en Java:
try{ int divide = 2/0; }catch(ArithmeticException ex){ ex.printStackTrace(); } int[] arreglo = {1,2,3}; try{ int numero = arreglo[3]; } catch(ArrayIndexOutOfBoundsException ex){ ex.printStackTrace(); } catch(Exception ex){ ex.printStackTrace(); } try{ int entero = Integer.parseInt("23f"); }catch(NumberFormatException ex){ ex.printStackTrace(); } String cadena = null; try{ boolean vacio = cadena.isEmpty(); }catch(NullPointerException ex){ ex.printStackTrace(); }
Lo que pretendemos hacer en el código de Java es:
- Realizar una operación de división por cero.
- Acceder a un índice inexistente de un arreglo de solo 3 elementos.
- Parsear un número a tipo entero con formato incorrecto.
- Verificar si una cadena está vacía, pero su valor es null.
El equivalente en Rust sería algo como esto:
excepciones.rs
fn main() { let num1:i32 = 2; let num2:i32 = 0; let divide:i32 = num1 / num2; match num1.checked_div(num2) { Some(_) => println!("Division hecha"), None => println!("Arithmetic error: Division by zero"), } let arreglo = [1, 2, 3]; match arreglo.get(3) { Some(numero) => println!("Numero: {}", numero), None => println!("Error: Index out of bounds"), } match "23f".parse::<i32>() { Ok(entero) => println!("Numero parseado: {}", entero), Err(e) => println!("Number format error: {:?}", e), } let cadena: Option<&str> = None; match cadena { Some(s) => println!("Esta vacio?: {}", s.is_empty()), None => println!("Error: Null pointer (None value)"), } }
Todo bien hasta aquí. Pero, ¿qué pasa si compilo el programa?
$ rustc excepciones.rs
Salida:
warning: unused variable: `divide` --> excepciones.rs:5:9 | 5 | let divide:i32 = num1 / num2; | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_divide` | = note: `#[warn(unused_variables)]` on by default error: this operation will panic at runtime --> excepciones.rs:5:22 | 5 | let divide:i32 = num1 / num2; | ^^^^^^^^^^^ attempt to divide `2_i32` by zero | = note: `#[deny(unconditional_panic)]` on by default error: aborting due to 1 previous error; 1 warning emitted
El compilador sabe que la operación que tratamos de hacer trata de realizar una división entre cero. Lo cual provocará que la compilación sea abortada. Comentaremos ese intento de manejo de excepción.
fn main() { /*let num1:i32 = 2; let num2:i32 = 0; let divide:i32 = num1 / num2; match num1.checked_div(num2) { Some(_) => println!("Division hecha"), None => println!("Arithmetic error: Division by zero"), }*/ let arreglo = [1, 2, 3]; match arreglo.get(3) { Some(numero) => println!("Numero: {}", numero), None => println!("Error: Index out of bounds"), } match "23f".parse::<i32>() { Ok(entero) => println!("Numero parseado: {}", entero), Err(e) => println!("Number format error: {:?}", e), } let cadena: Option<&str> = None; match cadena { Some(s) => println!("Esta vacio?: {}", s.is_empty()), None => println!("Error: Null pointer (None value)"), } }
Volvemos a compilar.
$ rustc excepciones.rs
Salida:
Error: Index out of bounds Number format error: ParseIntError { kind: InvalidDigit } Error: Null pointer (None value)
¡El programa falló satisfactoriamente!
Y está bien, es lo que queríamos. Ahora quitamos el comentario multilínea del bloque y cambiemos el valor del num2.
fn main() { let num1:i32 = 2; let num2:i32 = 2; let divide:i32 = num1 / num2; match num1.checked_div(num2) { Some(_) => println!("Division hecha"), None => println!("Arithmetic error: Division by zero"), } let arreglo = [1, 2, 3]; match arreglo.get(3) { Some(numero) => println!("Numero: {}", numero), None => println!("Error: Index out of bounds"), } match "23f".parse::<i32>() { Ok(entero) => println!("Numero parseado: {}", entero), Err(e) => println!("Number format error: {:?}", e), } let cadena: Option<&str> = None; match cadena { Some(s) => println!("Esta vacio?: {}", s.is_empty()), None => println!("Error: Null pointer (None value)"), } }
Compilemos y veamos el resultado:
$ rustc excepciones.rs
Salida:
Division hecha Error: Index out of bounds Number format error: ParseIntError { kind: InvalidDigit } Error: Null pointer (None value)
Para forzar a que nos de una excepción modificaremos el bloque de la divisón por cero.
fn main() { let num1:i32 = 2; let num2:i32 = 0; match num1.checked_div(num2) { Some(result) => println!("Division hecha: {}", result), None => println!("Arithmetic error: Division by zero"), } let arreglo = [1, 2, 3]; match arreglo.get(3) { Some(numero) => println!("Numero: {}", numero), None => println!("Error: Index out of bounds"), } match "23f".parse::<i32>() { Ok(entero) => println!("Numero parseado: {}", entero), Err(e) => println!("Number format error: {:?}", e), } let cadena: Option<&str> = None; match cadena { Some(s) => println!("Esta vacio?: {}", s.is_empty()), None => println!("Error: Null pointer (None value)"), } }
Compilamos y vemos el resultado:
$ rustc excepciones.rs
Salida:
Arithmetic error: Division by zero Error: Index out of bounds Number format error: ParseIntError { kind: InvalidDigit } Error: Null pointer (None value)
¡El manejo de excepciones en Rust ha funcionado!
Rust es un lenguaje potente y robusto que ha tomado lo mejor de lenguajes como Java, C# y C++ y ha descartado lo que no le sirve. Eso ha hecho que sea más tolerante a fallos.
Continuaremos con esta serie sobre Rust en próximas entregas.
Enlaces:
https://www.rust-lang.org/https://stackoverflow.com/questions/66602948/is-there-a-way-to-catch-division-by-zero-errors-without-checking-in-advance
https://codemonkeyjunior.blogspot.com/2025/07/programando-en-c-no-8-manejo-de.html
Comentarios
Publicar un comentario