A "heretic's" view of Rust error-handling

⚓ Rust    📅 2026-04-24    👤 surdeus    👁️ 1      

surdeus

Don't take the following too serious, I just want to point out that the "thou shalt not panic" paradigm also has downsides, particularly in the hands of less experienced developers like me.

It also impacts APIs since returning (meaningful) values for further use by an API becomes way more cumbersome.

As a Java-programmer, I get the checked exception feeling :zipper_mouth_face:

Q1: Is there a universal way of wrapping conformant Rust code so you don't have to check every statement?
Q2: Does the former require the use of the ?-operator by the underlying code?

A small example:

use std::str::FromStr;

struct Demo {
    vector: Vec<f64>
}

impl Demo {
    fn new() -> Demo {
        Demo{vector: Vec::new()}
    }

    fn add(&mut self, f64_string: &str) -> Result<(), Box<dyn std::error::Error>> {
        let result = f64::from_str(f64_string)?;
        self.vector.push(result);
        Ok(())
    }

    fn add_with_panic(&mut self, f64_string: &str) -> usize {
        match f64::from_str(f64_string) {
            Ok(value) => {
                self.vector.push(value);
            }
            Err(_e) => {
                panic!("Invalid float: {f64_string}");
            }
        }
        self.vector.len()
    }
}
fn main() {
    let mut a = Demo::new();
    let _ = a.add("5.7");
    // SILENTLY FAIL
    let _ = a.add("pretty bad");
    let n = a.add_with_panic("6.0");
    println!("There are {n} elements in the vector");
    let _ = a.add_with_panic("Not really a number");
}

Result:

There are 2 elements in the vector

thread 'main' (38473370) panicked at src/main.rs:24:17:
Invalid float: Not really a number

21 posts - 8 participants

Read full topic

🏷️ Rust_feed