Rust 相当于 try-catch 语句是什么? [英] What is the Rust equivalent to a try-catch statement?
问题描述
是否可以在 Rust 中一次处理多个不同的错误而不是单独处理而不使用附加功能?简而言之:什么是 Rust 等价于 try-catch 语句?
Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions? In short: what is the Rust equivalent to a try-catch statement?
这样的功能(使用 进行一流的错误处理?
和 catch
) 早在 2016 年就被建议了,但我不知道结果如何以及 2019 年针对此类问题的解决方案会是什么样子.
A feature like this (First-class error handling with ?
and catch
) was suggested back in 2016, but I can't tell what came out of it and how a 2019 solution for such a problem might look like.
例如,做这样的事情:
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.
My program has a function which checks a variety of different places in the registry for different data values and returns some aggregate data. It would need to use many of these try-cache statements with try-catch inside of other try-catch inside of loops.
推荐答案
Rust 中没有 try catch 语句.最接近的方法是 ?
运算符.
There is no try catch statement in Rust. The closest approach is the ?
operator.
但是,您最终不必创建函数和match
语句来解决它.您可以在您的范围内定义一个闭包并在闭包内使用 ?
运算符.然后抛出被保存在闭包返回值中,你可以在任何你想要的地方捕捉它,如下所示:
However, you do not have to create a function and a match
statement to resolve it in the end. You can define a closure in your scope and use ?
operator inside the closure. Then throws are held in the closure return value and you can catch this wherever you want like following:
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");
}
}
是否可以在不使用其他函数的情况下一次处理多个不同的错误,而不是在 Rust 中单独处理?
Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions?
有一个 无论如何 板条箱用于现在主要推荐 Rust 中的错误管理.
There is a anyhow crate for the error management in Rust mostly recommended nowadays.
作为替代,有一个失败 用于 Rust 错误管理的箱子.使用 Failure
,您可以链接、转换、连接错误.将错误类型转换为一种常见类型后,您可以轻松捕获(处理)它.
As an alternative, There is a failure crate for the error management in Rust. Using Failure
, you can chain, convert, concatenate the errors. After converting the error types to one common type, you can catch (handle) it easily.
这篇关于Rust 相当于 try-catch 语句是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!