Appearance
Day 13 - 错误处理
panic!
rust
panic!("something wrong");
// 处理panic
std::panic::catch_unwind(|| {
// 可能panic的代码
});? 运算符
rust
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}自定义错误
rust
use std::fmt;
#[derive(Debug)]
struct MyError(String);
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for MyError {}📅 学习进度
| Day | 主题 | 状态 |
|---|---|---|
| 01-12 | 基础 | ✅ |
| 13 | 错误处理 | ✅ |
| 14 | 智能指针 | ⬜ |
