Skip to content

错误处理

Panic

设置panic时直接退出

1
2
[profile.release]
panic = 'abort'

设置panic:

1
panic!("crash and burn");

Rusult

错误处理:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use std::fs::File;
use std::io::ErrorKind;
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!("Problem {:?}", e),
        },
        other => panic!("Other {:?}", other),
    },
};

失败时自动panic:

1
2
let f = File::open("hello.txt").unwrap();
let f = File::open("hello.txt").expect("Failed to open hello.txt");

错误上报:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use std::io;
use std::io::Read;
use std::fs::File;

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),
    }
}

?可以自动返回Error:

1
2
3
4
5
6
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)
}
可以连写:
1
2
3
4
5
6
7
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)
}

在main函数中使用?:

1
2
3
4
5
fn main() -> Result<(), Box<dyn Error>> {
    let f = File::open("hello.txt")?;

    Ok(())
}