error-handling - Rust 中的 try-catch 语句是什么?

标签 error-handling rust try-catch

是否可以一次处理多个不同的错误,而不是在 Rust 中单独处理而不使用额外的函数?简而言之:Rust 中什么是 try-catch 语句?

像这样的功能 (First-class error handling with ? and catch) 早在 2016 年就有人提出过,但我不知道它的结果是什么,也不知道 2019 年针对此类问题的解决方案会是什么样子。

例如,做这样的事情:

try {
    do_step_1()?;
    do_step_2()?;
    do_step_3()?;
    // etc
} catch {
    alert_user("Failed to perform necessary steps");
}

代替:

match do_steps() {
    Ok(_) => (),
    _ => alert_user("Failed to perform necessary steps")
}

// Additional function:
fn do_steps() -> Result<(), Error>{
    do_step_1()?;
    do_step_2()?;
    do_step_3()?;
    // etc
    Ok(())
}

我的程序有一个函数,它检查注册表中不同位置的不同数据值并返回一些聚合数据。它需要在循环内的其他 try-catch 中使用许多 try-cache 语句和 try-catch。

最佳答案

Rust 中没有 try catch 语句。最接近的方法是 ? 运算符。

但是,您不必创建函数和 match 语句来最终解析它。您可以在范围内定义闭包,并在闭包内使用 ? 运算符。然后 throws 保存在闭包返回值中,你可以在任何你想要的地方捕获它,如下所示:

fn main() {
    let do_steps = || -> Result<(), MyError> {
        do_step_1()?;
        do_step_2()?;
        do_step_3()?;
        Ok(())
    };

    if let Err(_err) = do_steps() {
        println!("Failed to perform necessary steps");
    }
}

Playground

Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions?

有一个anyhow用于 Rust 中的错误管理的箱子现在最受推荐。

作为替代方案,有一个 failure Rust 中错误管理的箱子。使用 Failure,您可以链接、转换、连接错误。将错误类型转换为一种常见类型后,您可以轻松捕获(处理)它。

关于error-handling - Rust 中的 try-catch 语句是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755552/

相关文章:

C++错误处理返回值错误返回

python-3.x - 如何在使用带有 for 循环的请求时忽略 HTTP 错误?

rust - 装饰器模式和不可变引用

struct - rust:如何使用引用外部值的回调编写 `impl`

具有可为空选项字段的 Rust 结构

java - 最后有时让我感到困惑

error-handling - PJSIP错误代码

python-3.x - 如果Try语句

c# - ASP.NET MVC 中的全局错误处理。可能的?

java - 从类内的多个方法捕获异常