Rust基础(8)-错误处理及测试

错误处理及测试

1. 错误处理

  • rust语言将错误分为两类:可恢复错误和不可恢复错误
    1. 可恢复错误通常代表向用户报告错误和重试操作是合理的情况,例如未找到文件。rust中使用Result<T,E>来实现
    2. 不可恢复错误是bug的同义词,如尝试访问超过数组结尾的位置。rust中通过panic!来实现

1.1 panic!

1
2
3
fn main() {
panic!("crash here")
}

1.2 BACKTRACE=1

调试时使用,BACKTRACE非0表示详细打出执行过程

1
RUST BACKTRACE=1 cargo run

1.3 RESULT<T,E>

原型为:

1
2
3
4
enum Result<T,E>{
Ok(T),
Err(E),
}

案例:

1
2
3
4
5
6
7
8
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
let r = match f {
Ok(file) => file,
Err(error) => panic!("error:{:?}",error),
};
}

1.3.1 简写方式1

1
2
3
4
use std::fs::File;
fn main() {
let f = File::open("hello.txt").unwrap();
}

1.3.2 简写方式2

1
2
3
4
use std::fs::File;
fn main() {
let f = File::open("hello.txt").expect("Filed to open hello.txt");
}

1.4 传播错误

当编写一个函数,但是该函数可能会失败,此时除了在函数中处理错误外,还可以将错误传给调用者,让调用者决定如何处理,这被称为传播错误

1.4.1 基本实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use std::io;
use std::io::Read;
use std::fs::File;

fn main() {
let r = read_username_from_file();
match r {
Ok(s) => println!("s = {}",s),
Err(e) => println!("err = {:?}",e),
}
}

fn read_username_from_file() -> Result<String, io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(error ) => return Err(error)
};
let mut s = String::new();
match f.read_to_string(&mut s){
Ok(_) => Ok(s),
Err(error) => return Err(error),
}
}

1.4.2 精简实现-推荐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::io;
use std::io::Read;
use std::fs::File;

fn main() {
let r = read_username_from_file();
match r {
Ok(s) => println!("s = {}",s),
Err(e) => println!("err = {:?}",e),
}
}

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)
}

1.4.3 进一步精简实现-推荐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::io;
use std::io::Read;
use std::fs::File;

fn main() {
let r = read_username_from_file();
match r {
Ok(s) => println!("s = {}",s),
Err(e) => println!("err = {:?}",e),
}
}

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)
}

测试

测试目录下执行:

1
cargo test

代码:
创建mod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
pub mod dog{
pub fn hello(){
println!("wangwang")
}

pub fn is_dog() -> bool{
true
}
}

pub mod cat{
pub fn hello(){
println!("miaomiao")
}

pub fn is_cat() -> bool{
true
}
}

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pub mod animal;

#[cfg(test)]
mod tests {
use crate::animal::*;

#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}

#[test]
fn use_cat(){
//cat::hello();
assert_eq!(true,cat::is_cat());
}

#[test]
fn use_dot(){
assert_eq!(true,dog::is_dog());
}
}

总结

本文编辑完毕

参考

[1] Rust 程序设计语言

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信