Rust编程语言之错误处理一、panic!不可恢复的错误Rust错误处理概述Rust的可靠性:错误处理大部分情况下:在编译时提示错误,并处理错误的分类:可恢复例如文件未找到,可再次尝试不可恢复bug,例如访问的索引超出范围Rust没有类似异常的机制
例子:Cargo.toml 文件
[package]
name = "vector_demo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[profile.release]
panic = 'abort'
例子:src/main.rs 文件
fn main() {
// panic!("crash and burn");
let v = vec![1, 2, 3];
v[99]; // panic
}
enum Result<T, E> {
Ok(T),
Err(E),
}
use std::fs::File
fn main() {
let f = File::open("hello.txt");
}
use std::fs::File
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => {
panic!("Error opening file {:?}", error)
}
};
}
use std::fs::File
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Error creating file: {:?}", e),
},
other_error = panic!("Error opening the file: {:?}", other_error),
},
};
}
use std::fs::File
fn main() {
let f = File::open("hello.txt").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Error creating file: {:?}", error);
})
} else {
panic!("Error opening the file: {:?}", error);
}
});
}
use std::fs::File
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => {
panic!("Error opening file {:?}", error)
}
};
let f = File::open("hello.txt").unwrap(); // 错误信息不可自定义
}
use std::fs::File
fn main() {
let f = File::open("hello.txt").expect("无法打开文件 hello.txt");
}
use std::fs::File;
use std::io;
use std::io::Read;
fn read_username_from_file() -> Result<String, io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
fn main() {
let result = read_username_from_file();
}
use std::fs::File;
use std::io;
use std::io::Read;
fn read_username_from_file() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
fn main() {
let result = read_username_from_file();
}
Trait std::convert::From 上的 from 函数:
被 ? 所应用的错误,会隐式的被 from 函数处理
当 ? 调用 from 函数时:
用于:针对不同错误原因,返回同一种错误类型
链式调用
use std::fs::File;
use std::io;
use std::io::Read;
fn read_username_from_file() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
fn main() {
let result = read_username_from_file();
}
use std::fs::File;
fn main() {
let f = File::open("hello.txt")?; // 报错
}
use std::error::Error;
use std::fs::File;
fn main() -> Result<(), Box<dyn Error>> {
let f = File::open("hello.txt")?;
Ok(())
}
Box<dyn Error>
是 Trait 对象:
use std::net::IpAddr;
fn main() {
let home: IpAddr = "127.0.0.1".parse().unwrap();
}
fn main() {
loop {
// ...
let guess = "32";
let guess: i32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
if guess < 1 || guess > 100 {
println!("The secret number will be between 1 and 100.");
continue;
}
// ...
}
}
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value >100 {
panic!("Guess value must be between 1 and 100, got {}", value);
}
Guess {value}
}
pub fn value(&self) -> i32 {
self.value
}
}
fn main() {
loop {
// ...
let guess = "32";
let guess: i32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
let guess = Guess::new(guess);
// ...
}
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!