走进 Rust:异常处理

Rust About 1,021 words

抛出异常

使用panic!宏抛出异常。

fn main() {
    panic!("crash and burn");
}

处理异常

使用Result枚举处理异常。

enum Result<T, E> {
    Ok(T),
    Err(E),
}

示例:使用match匹配枚举中的类型。

use std::fs::File;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(error) => {
            panic!("Problem opening the file: {:?}", error)
        },
    };
}

传播错误:?运算符

如果Result的值是Ok,这个表达式将会返回Ok中的值而程序将继续执行。如果值是ErrErr中的值将作为整个函数的返回值,就像使用了return关键字一样,这样错误值就被传播给了调用者。

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 read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();

    File::open("hello.txt")?.read_to_string(&mut s)?;

    Ok(s)
}

Rust封装好了异常处理后的读文件的API

use std::io;
use std::fs;

fn read_username_from_file() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}
Views: 2,505 · Posted: 2020-07-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh