-
Notifications
You must be signed in to change notification settings - Fork 0
/
23_errors.rs
89 lines (69 loc) · 1.93 KB
/
23_errors.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::fs::File;
use std::io::ErrorKind;
use std::io::Read;
fn main() {
let f = File::open("hello.txt");
// Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })
println!("{:?}", f);
let _f1 = match f {
Ok(file) => file,
Err(_error) => {
panic!("File not found")
}
};
// Match error types
let f = File::open("hello.txt");
let _f2 = match f {
Ok(file) => file,
Err(ref error) if error.kind() == ErrorKind::NotFound => {
match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => {
panic!("Not able to create file {:?}", e)
}
}
},
Err(error) => {
panic!("Unable to Open File {:?}", error);
}
};
// Unwrap
let _f = File::open("abc.txt").unwrap(); // Calls panic! for us when file not found
// Expect
let _f = File::open("abc.txt").expect("failed"); // Returns failed
// Propagating errors
let output = read();
match output {
Ok(fi) => println!("{:?}", fi),
Err(e) => println!("{:?}", e),
}
// Propagating using ?
let output = read_q();
match output {
Ok(fi) => println!("{:?}", fi),
Err(e) => println!("{:?}", e),
}
// Throws an unrecoverable error
panic!("Checking how panic works");
let a = [1,2,3];
// Throws unrecoverable error - out of bounds
a[99];
}
fn read() -> Result<String, std::io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
fn read_q() -> Result<String, std::io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}