Skip to content

Commit 6fd4aeb

Browse files
committed
feat: add (unfinished) ErrorHandling
1 parent baec64d commit 6fd4aeb

File tree

3 files changed

+172
-3
lines changed

3 files changed

+172
-3
lines changed

.gitignore

+4-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,7 @@ Cargo.lock
1616
Output/*
1717

1818
.idea/
19-
.vscode/
19+
.vscode/
20+
21+
# M
22+
carg.toml
+56-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,59 @@
11
#![allow(non_snake_case)]
2-
/// <WRITE DESCRIPTION HERE>
2+
3+
mod ReturningResults;
4+
5+
use std::fs::File;
6+
use std::os::unix::fs::PermissionsExt; // This probably doesn't on windows
7+
use std::io::ErrorKind;
8+
9+
/// Handling errors in Rust
310
fn main() {
4-
println!("Hello, world!");
11+
// We can intentionally panic with panic!()
12+
//panic!("oops");
13+
14+
let v = vec![1, 2, 3];
15+
// v[99]; // Oh no! index 99 doesn't exist! BAM CRASH
16+
17+
18+
// Let's handle potential errors
19+
let readme_file_result = File::open("README.md");
20+
21+
let readme_file = match readme_file_result {
22+
Ok(file) => {
23+
println!("DEBUG: The file was correctly read. \nThe permission mode of the file is: {:?}", file.metadata().unwrap().permissions().mode());
24+
file
25+
}, // return the file
26+
Err(error) => {
27+
panic!("The file had a problem opening.\nError: {:?}", error)
28+
}
29+
};
30+
31+
// Let's extend this a little bit.
32+
let cargo_toml_file_result = File::open("carg.toml");
33+
34+
let cargo_toml = match cargo_toml_file_result {
35+
Ok(file) => {
36+
println!("The file was correctly read. \nThe permission mode of the file is: {:?}", file.metadata().unwrap().permissions().mode());
37+
file
38+
}, // return the file
39+
Err(error) => match error.kind() {
40+
ErrorKind::NotFound => {
41+
println!("The file was not found. Maybe you made a typo? ;) anyways i'll create it for you but you're not getting away with it next time");
42+
match File::create("carg.toml") {
43+
Ok(fc) => {
44+
println!("Done!");
45+
fc // Return the file
46+
},
47+
Err(error) => {
48+
panic!("Something bad happened! We can't create a file. ERROR: {error}")
49+
}
50+
}
51+
},
52+
other_error => {
53+
panic!("Problem opening the file: {:?}", other_error)
54+
}
55+
}
56+
};
57+
58+
ReturningResults::main()
559
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
use std::fs;
2+
use std::fs::File;
3+
use std::io::{self, Read};
4+
5+
pub fn main() {
6+
// We use unwrap() here to use the String inside the Result our function returned. If an error happened it will panic accordingly.
7+
// V
8+
let readme_contents = read_file("README.md").unwrap();
9+
println!("The contents of the README are:\n {readme_contents}");
10+
11+
12+
// Exact same thing but cool
13+
let readme_contents = read_file_cool("README.md").unwrap();
14+
println!("The contents of the README are:\n {readme_contents}");
15+
16+
17+
// Exact same thing, but even cooler
18+
let readme_contents = read_file_quick("README.md").unwrap();
19+
println!("The contents of the README are:\n {readme_contents}");
20+
21+
22+
let really_green = Color::new(0,255,0);
23+
24+
println!("Really green G: {}", really_green.getG());
25+
}
26+
27+
28+
// This returns a Result<a,b> a is the content of the file read, and b is a possible error.
29+
fn read_file(file: &str) -> Result<String, io::Error> {
30+
// First read the file.
31+
let result = File::open(file);
32+
33+
// Then handle any errors that might have occurred
34+
let mut file = match result {
35+
Ok(file) => file, // if no errors occurred store the file in file
36+
Err(e) => return Err(e)
37+
};
38+
39+
// in here we store the contents of the file we just read
40+
let mut contents = String::new();
41+
42+
// attempt to read the file. If errors happen, we handle that
43+
match file.read_to_string(&mut contents) {
44+
Ok(_) => Ok(contents),// if no errors occurred we write it.
45+
Err(e) => Err(e) // else return the error
46+
}
47+
}
48+
49+
50+
// This is the same, but shorter
51+
fn read_file_cool(file: &str) -> Result<String, io::Error> {
52+
// first read the file. The ? means, do the operation, and if something happens return an error(Err(e)) and else return the result(Ok(r).
53+
let mut file = File::open(file)?; // ?
54+
55+
// store contents here
56+
let mut contents = String::new();
57+
58+
// write the data in contents. Errors are handled same as first line.
59+
file.read_to_string(&mut contents)?; // ?
60+
61+
// Then return the contents within an Ok(). This will work 100& because we have already outruled any other errors.
62+
Ok(contents)
63+
}
64+
65+
66+
// SHORTER
67+
fn read_file_cooler(file: &str) -> Result<String, io::Error> {
68+
// Init contents var
69+
let mut contents = String::new();
70+
71+
// read file
72+
File::open(file)? // <- handle errors
73+
// read contents
74+
.read_to_string(
75+
&mut contents // write contents
76+
)?; // <- handle errors
77+
78+
Ok(contents) // <- If no errors occured return the contents within an Ok()
79+
}
80+
81+
// SHOERR+RROURURPUYGIOP
82+
fn read_file_quick(file: &str) -> Result<String, io::Error> {
83+
// This litterly does everything we just made in one function.
84+
fs::read_to_string(file)
85+
// Looking at the source code of fs::read_to_string() this looks more reliable to use.
86+
}
87+
88+
89+
pub struct Color {
90+
r: u16,
91+
g: u16,
92+
b: u16,
93+
}
94+
95+
impl Color {
96+
pub fn new(r: u16, g: u16, b: u16) -> Color {
97+
if r > 255 || g > 255 || b > 255 {
98+
panic!("A color can't be more than 255!")
99+
}
100+
Color { r, g, b }
101+
}
102+
103+
pub fn getR(&self) -> u16 {
104+
self.r
105+
}
106+
pub fn getG(&self) -> u16 {
107+
self.g
108+
}
109+
pub fn getB(&self) -> u16 {
110+
self.b
111+
}
112+
}

0 commit comments

Comments
 (0)