什么是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-cache语句与try-catch和其他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中有一个 失败 板条箱用于错误管理。使用故障
,您可以链接,转换,连接错误。将错误类型转换为一种常见类型后,您可以轻松地捕获(处理)它。
Yes it is possible. 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屋!