📅  最后修改于: 2020-11-02 04:21:23             🧑  作者: Mango
在Rust中,错误可以分为两大类,如下表所示。
Sr.No | Name & Description | Usage |
---|---|---|
1 |
Recoverable Errors which can be handled |
Result enum |
2 |
UnRecoverable Errors which cannot be handled |
panic macro |
可恢复的错误是可以纠正的错误。当程序遇到可恢复的错误时,它可以重试失败的操作或指定备用操作。可恢复的错误不会导致程序突然失败。可恢复错误的一个示例是“找不到文件”错误。
不可恢复的错误导致程序突然失败。如果发生不可恢复的错误,程序将无法恢复到正常状态。它无法重试失败的操作或撤消错误。不可访问错误的一个示例是尝试访问数组末尾以外的位置。
与其他编程语言不同,Rust没有例外。它返回可恢复错误的枚举Result
恐慌!宏允许程序立即终止并向程序的调用者提供反馈。当程序达到不可恢复状态时,应使用它。
fn main() {
panic!("Hello");
println!("End of main"); //unreachable statement
}
在上面的示例中,程序在遇到紧急情况时将立即终止!宏。
thread 'main' panicked at 'Hello', main.rs:3
fn main() {
let a = [10,20,30];
a[10]; //invokes a panic since index 10 cannot be reached
}
输出如下所示-
warning: this expression will panic at run-time
--> main.rs:4:4
|
4 | a[10];
| ^^^^^ index out of bounds: the len is 3 but the index is 10
$main
thread 'main' panicked at 'index out of bounds: the len
is 3 but the index is 10', main.rs:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.
一个程序可以引起恐慌!宏,如果违反业务规则,如下例所示-
fn main() {
let no = 13;
//try with odd and even
if no%2 == 0 {
println!("Thank you , number is even");
} else {
panic!("NOT_AN_EVEN");
}
println!("End of main");
}
如果分配给变量的值为奇数,则上面的示例将返回错误。
thread 'main' panicked at 'NOT_AN_EVEN', main.rs:9
note: Run with `RUST_BACKTRACE=1` for a backtrace.
枚举结果–
enum Result {
OK(T),
Err(E)
}
让我们借助示例了解这一点-
use std::fs::File;
fn main() {
let f = File::open("main.jpg");
//this file does not exist
println!("{:?}",f);
}
如果文件已经存在,则程序返回OK(File),如果找不到文件,则返回Err(Error) 。
Err(Error { repr: Os { code: 2, message: "No such file or directory" } })
现在让我们看看如何处理Err变体。
以下示例处理使用match语句打开文件时返回的错误
use std::fs::File;
fn main() {
let f = File::open("main.jpg"); // main.jpg doesn't exist
match f {
Ok(f)=> {
println!("file found {:?}",f);
},
Err(e)=> {
println!("file not found \n{:?}",e); //handled error
}
}
println!("end of main");
}
注意:尽管找不到文件,程序仍会打印主事件的结尾。这意味着程序已正常处理错误。
file not found
Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }
end of main
如果数字不是偶数, is_even函数将返回错误。 main()函数处理此错误。
fn main(){
let result = is_even(13);
match result {
Ok(d)=>{
println!("no is even {}",d);
},
Err(msg)=>{
println!("Error msg is {}",msg);
}
}
println!("end of main");
}
fn is_even(no:i32)->Result {
if no%2==0 {
return Ok(true);
} else {
return Err("NOT_AN_EVEN".to_string());
}
}
注意–由于main函数处理错误,因此将打印main语句的末尾。
Error msg is NOT_AN_EVEN
end of main
标准库包含两个辅助方法,它们都枚举-Result
Sr.No | Method | Signature & Description |
---|---|---|
1 | unwrap |
unwrap(self): T Expects self to be Ok/Some and returns the value contained within. If it is Err or None instead, it raises a panic with the contents of the error displayed. |
2 | expect |
expect(self, msg: &str): T Behaves like unwrap, except that it outputs a custom message before panicking in addition to the contents of the error. |
unwrap()函数返回操作成功的实际结果。如果操作失败,它将返回带有默认错误消息的紧急消息。此函数是match语句的简写。这在下面的示例中显示-
fn main(){
let result = is_even(10).unwrap();
println!("result is {}",result);
println!("end of main");
}
fn is_even(no:i32)->Result {
if no%2==0 {
return Ok(true);
} else {
return Err("NOT_AN_EVEN".to_string());
}
}
result is true
end of main
修改上面的代码以将一个奇数传递给is_even()函数。
unwrap()函数将出现错误并返回默认错误消息,如下所示
thread 'main' panicked at 'called `Result::unwrap()` on
an `Err` value: "NOT_AN_EVEN"', libcore\result.rs:945:5
note: Run with `RUST_BACKTRACE=1` for a backtrace
如果出现紧急情况,程序可以返回自定义错误消息。这在以下示例中显示-
use std::fs::File;
fn main(){
let f = File::open("pqr.txt").expect("File not able to open");
//file does not exist
println!("end of main");
}
函数Expect()与unwrap()类似。唯一的区别是可以使用期望显示自定义错误消息。
thread 'main' panicked at 'File not able to open: Error { repr: Os
{ code: 2, message: "No such file or directory" } }', src/libcore/result.rs:860
note: Run with `RUST_BACKTRACE=1` for a backtrace.