Intro to Rust-lang (Error Handling)
Skills:
ML Maths Basics60%
Key Takeaways
This video introduces Rust-lang error handling using Result and Option Enums, covering basic methods for error checking and propagation, as well as the use of the ? operator for concise error handling. It also touches on Rust's type system and its role in reducing error checks.
Full Transcript
hey guys welcome back to introduction to rust my name is tensor today we're gonna be looking at error handling errors are sort of effective life any program you write you're going to run into some kind of bug or error maybe even unnecessary side-effects and things like that so we've already mentioned that rust doesn't use the idea of nil and instead it uses the option and result enums in its place and we can use these abstractions to really good effect especially when it comes to error handling to rust divides its errors into two major groups recoverable and unrecoverable errors recoverable errors are errors in which situation occurs and maybe the program doesn't entirely shut down and it just keeps running and maybe it's just causing a unnecessary side-effect an unrecoverable error on the other hand causes the program to have failure so the program might stop maybe a thread will completely shut down all right so let's just take a look at some very basic unrecoverable errors first so here's a very simple example we have a vector with two elements in it and we're trying to call the 50th index of this vector we get what's called a panic so it says here thread main panicked at index out of bounds the line is 2 but the index is 50 so it's actually telling us what the problem is we can see a more verbose error message here if we actually set the global environment variable rust back-trace to 1 in Windows we can simply just call the set keyword and then just writing rust back trace equals 1 and then we can run cargo again we get a bunch of different steps that actually happened as this panic went and happened in our program now if you want to set it back to the normal version you can just reset the variable back to zero with Linux or Mac if you want to look at the back trace you just call rust back trace 1 and then you call cargo run after it so rest has a macro called panic and this will allow us to force a panic in our program if you look at this example we have a function called exit which just takes an i-32 and if that I 32 happens to be equal to 0 then we just panic we pass back this string here otherwise we just print out this string here so here we can just pass in exit 1 and then exit zero and of course this will force a panic for us so first we get our things are fine string and then we get thread main panic that we got zero forcing the program to actually shut down like this can be pretty useful in specific cases alright so by default the panic occurs when the program starts what's called unwinding so the compiler has sort of walks back up the stack and it cleans up the memory in the data and when the panic happens it happens after this happens all right so most errors are not unrecoverable so most errors are not serious enough to require the program to stop entirely and we use these two abstractions to help us with that we've already kind of talked about the result and option enums thus far but they are pretty useful for error handling as well so the result enum has two generics T&E and this allows both of the types inside of the result enum to have their own individual type the value inside of our okay here can be different from the value inside of our error with our option enum we either get some with the value inside of it or we just get none so let's go back to our exit example here so here we're just calling a panic if we get x equals 0 we can rewrite this with an option instead of an i-32 so if we make X an option a 32 then we need to do a match statement on X so that we can unwrap the option here all right so here's our exit function rewritten for dealing with an option for some 0 we panic and we say we got 0 then for some X which means anything other than 0 we then print it out inside of a string here and then we say things are fine and then finally if we get none then we just print out we got nothing here we get our first one so we get 1 and it says things are fine then we get 10 things are fine then we get nothing and then finally we have a panic so options are pretty useful when dealing with error handling though they're not as nuanced as the result enum so here's a pretty simple example of a result function so we've already kind of looked at this this is opening a file so we will either get a error here or we will actually get our file so we want to open an external file called text txt this function will actually return result with you the file in it or within error so we bind that to F and then we can pattern match through it so that we can deconstruct the result and get the actual data out of it and then rebind it to F we can do the same with our error we get back an error we can automatically panic and then kick back the reason so that you can read why we can go even further with our pattern matching here and make it so that we pattern match on specific use cases so in this case we are saying okay let's match on F if we get a file then we just want to pass back the file if we get an error then we want to check the error and we're gonna say okay well if the error and the error kind is that the fire was not found then we can match on file create text exe so this will actually create the file and if this succeeds then we just send back the file otherwise we send back an error and panic that says cannot create the file and we set the air inside of that and then our other branch of course is if the file does exist and then there's another error that happens then we just pass back a panic this is could not open the file so this kind of pattern matching is extremely useful but it's also very verbose and it's a pattern that you see a lot inside of rust and as a result creators of rust decided to implement what are essentially functions that do exactly what we're doing here with this match block so the first method that sort of does what we were doing with that match block is called unwrap now unwrap will just unwrap the actual data from the result or the option so option and result both have methods called unwrap and they do essentially the same thing it just takes in the result and it outputs the data we also have another method called expect now expect is like unwrapped in that it unwraps the actual file if we get back in okay but if we don't get back in okay and instead we get back an error then it automatically will panic for us and then send back this message so in this case it'll say could not open this file now both expect and unwrap are pretty useful for when you're first creating your program if you don't really want to have to deal with errors that time you can just use unwrapped or use expect to just have some very rudimentary error handling inside of your project alright so consider this example for a moment so we've taken our reading of file and we've put it inside of its own function and we've also added a few other things inside of it and we're passing back a result with a string and an i/o error the reason we're doing this is because we want to follow a pattern called propagating errors too rather than handling the error inside of the function itself we're actually going to pass back the error so that we can handle it in our main function so if our function succeeds then obviously we just get back our file first from this match block and then we are able to read our file into a string and then just pass it back to our main function if we call it that if it fails however then we either return our error from the first match block here or we return our error here inside of the result this pattern of propagating errors is pretty common in rust and rust provides a specific operator to make this easier and first what we want to do is just remove the top match block then we want to make our F here immutable and we're going to put a question mark here at the end then for our second match block we're going to remove this part here and put another question mark so you can see here this is what a less verbose version of that same function will look like and the way that we cleaned it up is by adding these question mark operators here and here we had a match statement for this and then we had a match statement for this and now what we're doing is we're returning back an OK with our string inside this question mark like unwrapped and expanded after a result value is to find the work in almost the same way as our match expressions that we had before would have worked if we get back an OK from the result of either opening the file or reading the string then the program will continue as normal and then we'll send back the string inside of an ok here if the value is an error the value inside the error will be returned from the whole function as if we had the return keyword so the error value gets propagated to the calling code or a question mark like our unwrap and expect methods eliminates a lot of boilerplate code and it can help us really make things a lot cleaner here in fact we can actually further decrease the size of this function rather than having to method calls we can chain the two together we still keep the question marks here and this is effectively the same code as what we had before it it's just a little bit more concise and easier to read another thing to mention about this question mark is that it can only really be used inside of functions that return a result we can't use this in our main function here because our main function actually returns a unit type so just two parentheses like this if you see here we try to put a question mark here obviously it doesn't work so in coding around errors there are a few simple ideas that you kind of want to keep in mind if your code could end up in a bad state usually it's advisable to use a panic so things such as invalid values contradictory values or missing values those types of things should simply be dealt with by using panics or things that produce panics because bad state is not really something that you can expect to happen it does happen occasionally though if somebody does call your code and intentionally passes something that doesn't make sense then the best way to deal with it is of course to panic note the person who passed in the bad code or you also panic is pretty appropriate if you're calling external code that's out of your control if we're trying to parse JSON or reading from like a web server of any kind panics are pretty useful having lots of error checks and your functions would be very verbose and annoying though fortunately if you use Russ type system then the compiler will do many checks for you and it will make it so that you don't have to capture so many errors all right guys well I hope you enjoyed this tutorial if you did feel free to subscribe and like if you have any questions or comments leave them in the comment box below and if you just liked it then download it as much as you like have a good night guys
Original Description
In this video, we look at how we can use the Result and Option Enums to deal with Errors in Rust. We also look at some of the basic methods that are commonly used in place of pattern match statements to check errors.
Feel free to donate:
BTC: 1ExBSiaEa3pceW98eptJwzR9QHrYZ71Xit
ETH: 0xE448a8DDA5886C49d35B191B2F20630c103024c8
LTC: LXsKxF5JhmMtKgqfcUFdvcXVwiaSqxN9cP
Check out our Twitter: https://twitter.com/TensorProgram
Check out our Facebook: https://www.facebook.com/Tensor-Programming-1197847143611799/
Check out our Steemit: https://steemit.com/@tensor
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Tensor Programming · Tensor Programming · 53 of 60
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
▶
54
55
56
57
58
59
60
NodeJs, Text editors and IDEs
Tensor Programming
Vanilla JS todo App
Tensor Programming
Elm Tutorial part 1
Tensor Programming
Elm Lang Tutorial, Part 2
Tensor Programming
Elm Tutorial Part 3
Tensor Programming
Elm Tutorial Part 4 -- Analog Clock App
Tensor Programming
Elm Tutorial part 5 -- Snake Game
Tensor Programming
Elm Tutorial part 6 -- Calculator
Tensor Programming
Go Tutorial part 1 -- Hello World and Static File Server
Tensor Programming
Go Tutorial part 2 -- Web Crawler
Tensor Programming
Go Tutorial Part 3 (Web App part 1)
Tensor Programming
Go tutorial Part 4 (Web tutorial part 2) - Using templates
Tensor Programming
Go tutorial part 5 (web app part 3)
Tensor Programming
Go tutorial part 6 (webapp part 4)
Tensor Programming
Go tutorial part 7 (web app part 5)
Tensor Programming
Go tutorial part 8 (Web app part 6)
Tensor Programming
Go tutorial Part 9 (web tutorial part 7)
Tensor Programming
Go tutorial Part 10 (web app part 8)
Tensor Programming
Go tutorial Part 11 (Web app Part 9)
Tensor Programming
Go Tutorial Part 12 (Web app Part 10)
Tensor Programming
Go Tutorial Part 13 (Web app Part 11)
Tensor Programming
Looking at Elm 0.18
Tensor Programming
Go tutorial Part 14 (Web tutorial part 12)
Tensor Programming
Go tutorial Part 15 (Web tutorial part 13)
Tensor Programming
Go tutorial part 16 (web app part 14)
Tensor Programming
Elm Tutorial Part 7 (SPA part 1)
Tensor Programming
Elm Tutorial Part 8 (SPA Part 2)
Tensor Programming
Electron Elm Tutorial
Tensor Programming
Go tutorial part 17 (web app part 15)
Tensor Programming
Up and Coming Programming Languages and Technologies for 2017
Tensor Programming
elixir tutorial part 1
Tensor Programming
elixir tutorial part 2
Tensor Programming
Elixir tutorial Part 3 (GenServer and Supervisor)
Tensor Programming
Elixir Tutorial Part 4 (GenStage)
Tensor Programming
Elixir Tutorial Part 5 (Plug and Cowboy)
Tensor Programming
Phoenix Framework Tutorial Part 1 (elixir part 6)
Tensor Programming
Phoenix Framework Tutorial Part 2 (elixir part 7)
Tensor Programming
Phoenix Framework Tutorial Part 3 (elixir part 8)
Tensor Programming
A Intro to Clojure and Clojure Syntax
Tensor Programming
An Update about the channel
Tensor Programming
Intro to Rustlang (Setup and Primitives)
Tensor Programming
Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Tensor Programming
Intro to Rustlang (Ownership and Borrowing)
Tensor Programming
Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Tensor Programming
Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Tensor Programming
Intro to RustLang (Enums and Options)
Tensor Programming
Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Tensor Programming
Rustlang Project: Snake Game
Tensor Programming
Intro to Rustlang (Traits and Generic Types)
Tensor Programming
Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Tensor Programming
Intro to Rust-lang (Modules and Lifetimes)
Tensor Programming
Intro to Rust-lang (Macros and Metaprogramming)
Tensor Programming
Intro to Rust-lang (Error Handling)
Tensor Programming
Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Tensor Programming
Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Tensor Programming
Rustlang Project: Port Sniffer CLI
Tensor Programming
Rustlang Project: Chat Application
Tensor Programming
Rustlang Project: CLI Toy Blockchain
Tensor Programming
Intro to Rust-lang (Setting up a Development Environment)
Tensor Programming
Intro to Rust-lang (Building a Web API with Iron)
Tensor Programming
More on: ML Maths Basics
View skill →Related Reads
📰
📰
📰
📰
Neural Networks vs. Biological Neurons: A visual comparison of AI and the human brain.
Medium · Data Science
Conda Environment Naming: -n vs -p — Which One Should You Use?
Medium · Python
Comparing Two Eval Runs by Their Average Pass Rate Is the Wrong Test
Dev.to · Maya Andersson
ML Infrastructure vs. AI Infrastructure: Are They the Same Thing?
Dev.to · Conor Breathnach
🎓
Tutor Explanation
DeepCamp AI