当前位置:   article > 正文

Rust 错误处理 简记_rust backtrace

rust backtrace

Rust 错误处理

错误简介

Rust 有错误, 无异常, Rust 错误的两个主要类别:

  • 可恢复错误(recoverable), 如 Option<T> 或 Result<T, E>泛型
  • 不可恢复错误(unrecoverable), 如 panic!

panic!

当出现panic(恐慌)时, 有两种选择:

  • 展开(unwinding), 默认, Rust会回溯(backtrace)栈并清理遇到的每个函数的数据. Debug的时候可以 RUST_BACKTRACE=1 cargo runRUST_BACKTRACE=full cargo run 对 panic 回溯
  • 终止(abort), 不清理直接退出, 内存由操作系统清理, Release时可以在Cargo.toml文件设置panic时终止, 这样生成的二进制也会小一些, 设置如下
[profile.release]
panic = 'abort'
  • 1
  • 2

直接 panic

fn main() {
    panic!("crash and burn");
}

// thread 'main' panicked at 'crash and burn', src/main.rs:3:5
// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

panic 的发生(如除零, 数组越界, 缓冲区溢出等)

fn main() {
    let div = |x: i32, y: i32| -> i32 { x / y };
    println!("div(10, 0) = {}", div(10, 0));  // panic
}

// thread 'main' panicked at 'attempt to divide by zero', src/main.rs:3:41
// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

示例, 代码原型和测试都很适合 panic

Option

Option的原型是枚举

pub enum Option<T> {
    None,
    Some(T),
}
  • 1
  • 2
  • 3
  • 4

Rust没有null, 可以用Option的None, 碰到错误返回None

fn main() {
    let div = |x: i32, y: i32| -> Option<i32> {
        match y {
            0 => None,
            _ => Some(x / y),
        }
    };
    println!("div(10, 2) = {}", div(10, 2).unwrap());   // 5
    println!("div(10, 2) = {:?}", div(10, 2));        // Some(5)
    println!("div(10, 0) = {:?}", div(10, 0));      // None
    println!("div(10, 0) = {:?}", div(10, 0).unwrap_or(0));   // 0
    println!("div(10, 0) = {:?}", div(10, 0).unwrap_or_else(|| 0));   // 0
    // println!("div(10, 0) = {}", div(10, 0).unwrap()); // panic
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Result

Result的原型是枚举, 函数可以不管单个或多个错误是什么, 可以直接打印错误情况, 也可以直接往上抛, 透传错误, 看后人的智慧

enum Result<T, E> {
    Ok(T),
    Err(E),
}
  • 1
  • 2
  • 3
  • 4

返回 String 的例子, 结果参考注释

fn main() {
    let div = |x: i32, y: i32| -> Result<i32, String> {
        match y {
            0 => Err("Division by zero".to_string()),
            _ => Ok(x / y),
        }
    };
    println!("div(10, 2) = {}", div(10, 2).unwrap());   // 5
    println!("div(10, 0) = {}", div(10, 0).unwrap_err());   // Division by zero
    println!("div(10, 0) = {:?}", div(10, 0).err());    // Some("Division by zero")
    println!("div(10, 0) = {:?}", div(10, 0).ok()); // None
    println!("div(10, 0) = {:?}", div(10, 0).unwrap_or(0)); // 0
    println!("div(10, 0) = {:?}", div(10, 0).unwrap_or_else(|e| {
        println!("Error: {}", e);   // Error: Division by zero
        0   // 0 is the return value
    }));
    // println!("div(10, 0) = {}", div(10, 0).unwrap());    // panic
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

更多时候不返回String, 而是返回 std::io::Error

    let div = |x: i32, y: i32| -> Result<i32, std::io::Error> {
        match y {
            0 => Err(std::io::Error::new(std::io::ErrorKind::Other, "Division by zero")),
            _ => Ok(x / y),
        }
    };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

? 操作符, 类似 .unwrap()

fn main() {
    let read_file = |filename: &str| -> Result<String, std::io::Error> {
        let mut f = std::fs::File::open(filename)?;
        let mut s = String::new();
        std::io::Read::read_to_string(&mut f, &mut s)?;
        Ok(s)
    };
    match read_file("./Cargo.toml") {
        Ok(s) => println!("read_file(\"./Cargo.toml\") = {}", s),
        Err(e) => println!("read_file(\"./Cargo.toml\") = {:?}", e),
    }
    // Os { code: 2, kind: NotFound, message: "No such file or directory" }
    println!("read_file(\"./Cargo1.toml\") = {:?}", read_file("./Cargo1.toml").unwrap_err());
    // Some(Os { code: 2, kind: NotFound, message: "No such file or directory" })
    println!("read_file(\"./Cargo1.toml\") = {:?}", read_file("./Cargo1.toml").err());
    // None
    println!("read_file(\"./Cargo1.toml\") = {:?}", read_file("./Cargo1.toml").ok());
    // ""
    println!("read_file(\"./Cargo1.toml\") = {:?}", read_file("./Cargo1.toml").unwrap_or("".to_string()));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

main 也可以返回 Result, 这样可以通篇 ? 操作符, 有错误就直接panic, 停止程序的运行

fn main() -> Result<(), std::io::Error> {
    let div = |x: i32, y: i32| -> Result<i32, std::io::Error> {
        match y {
            0 => Err(std::io::Error::new(std::io::ErrorKind::Other, "Division by zero")),
            _ => Ok(x / y),
        }
    };
    println!("div(10, 2) = {}", div(10, 2)?);
    // Error: Custom { kind: Other, error: "Division by zero" }
    // println!("div(10, 0) = {:?}", div(10, 0)?);
    let read_file = |filename: &str| -> Result<String, std::io::Error> {
        let mut f = std::fs::File::open(filename)?;
        let mut s = String::new();
        std::io::Read::read_to_string(&mut f, &mut s)?;
        Ok(s)
    };
    // Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
    println!("read_file(\"temp.txt\") = {}", read_file("temp.txt")?);
    Ok(())
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

不返回 std::io::ErrorBox<std::io::Error>, 可以自定义Error对所有错误进行统一管理, 需要实现 Error, From等trait

// 可以把MyError放外面, main也不用返回std::io::Error
fn main() -> Result<(), std::io::Error> {
    #[derive(Debug)]
    enum MyError {
        DivByZero(String),
        Io(std::io::Error),
        Parse(std::num::ParseIntError),
    }
    impl From<std::io::Error> for MyError {
        fn from(err: std::io::Error) -> MyError {
            MyError::Io(err)
        }
    }
    impl From<std::num::ParseIntError> for MyError {
        fn from(err: std::num::ParseIntError) -> MyError {
            MyError::Parse(err)
        }
    }
    impl From<MyError> for std::io::Error {
        fn from(err: MyError) -> std::io::Error {
            match err {
                MyError::Io(err) => err,
                _ => std::io::Error::new(std::io::ErrorKind::Other, err),
            }
        }
    }
    impl std::fmt::Display for MyError {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match self {
                MyError::DivByZero(msg) => write!(f, "DivByZero({})", msg),
                MyError::Io(err) => write!(f, "Io({})", err),
                MyError::Parse(err) => write!(f, "Parse({})", err),
            }
        }
    }
    impl std::error::Error for MyError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            match self {
                MyError::Io(err) => Some(err),
                MyError::Parse(err) => Some(err),
                _ => None,
            }
        }
    }

    let div = |x: i32, y: i32| -> Result<i32, MyError> {
        match y {
            0 => Err(MyError::DivByZero("Division by zero".to_string())),
            _ => Ok(x / y),
        }
    };
    println!("div(10, 0) = {}", div(10, 0).unwrap_err()); // DivByZero(Division by zero)
    println!("div(10, 2) = {}", div(10, 2)?);

    let read_int = || -> Result<i32, MyError> {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        let n: i32 = input.trim().parse()?;
        Ok(n)
    };
    let x = read_int()?;
    println!("x = {}", x);

    let read_file = |filename: &str| -> Result<String, MyError> {
        let mut f = std::fs::File::open(filename)?;
        let mut s = String::new();
        std::io::Read::read_to_string(&mut f, &mut s)?;
        Ok(s)
    };
    let s = read_file("temp.rs")?;
    println!("s = {}", s);

    Ok(())
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

上面的一堆看着都头疼, 可以使用 dtolnay/thiserror: derive(Error) for struct and enum error types (github.com) 进行简化, Cargo.toml添加

[dependencies]
thiserror = "1.0.38"
  • 1
  • 2

然后main.rs就可以简写如下, 这样看着就清爽了很多

#[derive(Debug, thiserror::Error)]
enum MyError {
    #[error("Division by zero")]
    DivByZero,
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Parse error: {0}")]
    Parse(#[from] std::num::ParseIntError),
}

fn main() -> Result<(), MyError> {
    let div = |x: i32, y: i32| -> Result<i32, MyError> {
        match y {
            0 => Err(MyError::DivByZero),
            _ => Ok(x / y),
        }
    };
    println!("div(10, 0) = {}", div(10, 0).unwrap_err()); // DivByZero(Division by zero)
    println!("div(10, 2) = {}", div(10, 2)?);

    let read_int = || -> Result<i32, MyError> {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        let n: i32 = input.trim().parse()?;
        Ok(n)
    };
    let x = read_int()?;
    println!("x = {}", x);

    let read_file = |filename: &str| -> Result<String, MyError> {
        let mut f = std::fs::File::open(filename)?;
        let mut s = String::new();
        std::io::Read::read_to_string(&mut f, &mut s)?;
        Ok(s)
    };
    let s = read_file("temp.rs")?;
    println!("s = {}", s);

    Ok(())
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

参考

如有错误, 敬请指正, 参考如下:

欢迎扫描二维码关注微信公众号, 及时获取最新文章:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/951193
推荐阅读
相关标签
  

闽ICP备14008679号