赞
踩
Rust 有错误, 无异常, Rust 错误的两个主要类别:
Option<T> 或 Result<T, E>
泛型panic!
宏当出现panic(恐慌)时, 有两种选择:
RUST_BACKTRACE=1 cargo run
或 RUST_BACKTRACE=full cargo run
对 panic 回溯[profile.release]
panic = 'abort'
直接 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
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
示例, 代码原型和测试都很适合 panic
Option的原型是枚举
pub enum Option<T> {
None,
Some(T),
}
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
}
Result的原型是枚举, 函数可以不管单个或多个错误是什么, 可以直接打印错误情况, 也可以直接往上抛, 透传错误, 看后人的智慧
enum Result<T, E> {
Ok(T),
Err(E),
}
返回 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 }
更多时候不返回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),
}
};
? 操作符, 类似 .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())); }
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(()) }
不返回 std::io::Error
或 Box<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(()) }
上面的一堆看着都头疼, 可以使用 dtolnay/thiserror: derive(Error) for struct and enum error types (github.com) 进行简化, Cargo.toml添加
[dependencies]
thiserror = "1.0.38"
然后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(()) }
如有错误, 敬请指正, 参考如下:
欢迎扫描二维码关注微信公众号, 及时获取最新文章:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。