Rust错误处理
Rust中,错误处理是语言设计的核心部分,强调显式处理所有可能的错误路径,避免隐式的错误传播
一、错误处理的两大核心
- Option
: 表示一个值可能存在Some(T)或不存在(None) - Result<T, E>: 表示成功Ok(T)或Err(E)
fn read_file(path: &str) -> Result<String, std::io::Error> {
std::fs::read_to_string(path)
}
二、错误处理策略
- 快速失败:panic!
- 不可恢复错误(如内存耗尽、逻辑错误)
- 风险:终止线程,不清理资源
fn divide(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("除零错误");
}
return a / b;
}
- 显示处理match
let rust = read_file("config.toml")
match result {
OK(content) => println!("内容:{}", content),
Err(e) => eprintln!("错误: {}", e)
}
- 错误传播符:?,自动将错误向上层返回,简化链式调用
fn process_file() -> Result<String, std::io::Error> {
let content = read_file("data.txt")?; // 错误时直接返回
return OK(content);
}
- 自定义错误类型, 通过thiserror库简化实现
use thiserror::Error;
#[derive(Error, Debug)]
enum AppError {
#[error("IO错误: {0}")]
IO(#[from] std::io::Error),
#[error("解析错误:{0}")]
Parse(String),
}