Intro to Rust-lang (Error Handling)

Tensor Programming · Beginner ·📐 ML Fundamentals ·8y ago

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 NodeJs, Text editors and IDEs
NodeJs, Text editors and IDEs
Tensor Programming
2 Vanilla JS todo App
Vanilla JS todo App
Tensor Programming
3 Elm Tutorial part 1
Elm Tutorial part 1
Tensor Programming
4 Elm Lang Tutorial, Part 2
Elm Lang Tutorial, Part 2
Tensor Programming
5 Elm Tutorial Part 3
Elm Tutorial Part 3
Tensor Programming
6 Elm Tutorial Part 4 -- Analog Clock App
Elm Tutorial Part 4 -- Analog Clock App
Tensor Programming
7 Elm Tutorial part 5 -- Snake Game
Elm Tutorial part 5 -- Snake Game
Tensor Programming
8 Elm Tutorial part 6 -- Calculator
Elm Tutorial part 6 -- Calculator
Tensor Programming
9 Go Tutorial part 1 -- Hello World and Static File Server
Go Tutorial part 1 -- Hello World and Static File Server
Tensor Programming
10 Go Tutorial part 2 -- Web Crawler
Go Tutorial part 2 -- Web Crawler
Tensor Programming
11 Go Tutorial Part 3 (Web App part 1)
Go Tutorial Part 3 (Web App part 1)
Tensor Programming
12 Go tutorial Part 4 (Web tutorial part 2) - Using templates
Go tutorial Part 4 (Web tutorial part 2) - Using templates
Tensor Programming
13 Go tutorial part 5 (web app part 3)
Go tutorial part 5 (web app part 3)
Tensor Programming
14 Go tutorial part 6 (webapp part 4)
Go tutorial part 6 (webapp part 4)
Tensor Programming
15 Go tutorial part 7 (web app part 5)
Go tutorial part 7 (web app part 5)
Tensor Programming
16 Go tutorial part 8 (Web app part 6)
Go tutorial part 8 (Web app part 6)
Tensor Programming
17 Go tutorial Part 9 (web tutorial part 7)
Go tutorial Part 9 (web tutorial part 7)
Tensor Programming
18 Go tutorial Part 10 (web app part 8)
Go tutorial Part 10 (web app part 8)
Tensor Programming
19 Go tutorial Part 11 (Web app Part 9)
Go tutorial Part 11 (Web app Part 9)
Tensor Programming
20 Go Tutorial Part 12 (Web app Part 10)
Go Tutorial Part 12 (Web app Part 10)
Tensor Programming
21 Go Tutorial Part 13 (Web app Part 11)
Go Tutorial Part 13 (Web app Part 11)
Tensor Programming
22 Looking at Elm 0.18
Looking at Elm 0.18
Tensor Programming
23 Go tutorial Part 14 (Web tutorial part 12)
Go tutorial Part 14 (Web tutorial part 12)
Tensor Programming
24 Go tutorial Part 15 (Web tutorial part 13)
Go tutorial Part 15 (Web tutorial part 13)
Tensor Programming
25 Go tutorial part 16 (web app part 14)
Go tutorial part 16 (web app part 14)
Tensor Programming
26 Elm Tutorial Part 7 (SPA part 1)
Elm Tutorial Part 7 (SPA part 1)
Tensor Programming
27 Elm Tutorial Part 8 (SPA Part 2)
Elm Tutorial Part 8 (SPA Part 2)
Tensor Programming
28 Electron Elm Tutorial
Electron Elm Tutorial
Tensor Programming
29 Go tutorial part 17 (web app part 15)
Go tutorial part 17 (web app part 15)
Tensor Programming
30 Up and Coming Programming Languages and Technologies for 2017
Up and Coming Programming Languages and Technologies for 2017
Tensor Programming
31 elixir tutorial part 1
elixir tutorial part 1
Tensor Programming
32 elixir tutorial part 2
elixir tutorial part 2
Tensor Programming
33 Elixir tutorial Part 3 (GenServer and Supervisor)
Elixir tutorial Part 3 (GenServer and Supervisor)
Tensor Programming
34 Elixir Tutorial Part 4 (GenStage)
Elixir Tutorial Part 4 (GenStage)
Tensor Programming
35 Elixir Tutorial Part 5 (Plug and Cowboy)
Elixir Tutorial Part 5 (Plug and Cowboy)
Tensor Programming
36 Phoenix Framework Tutorial Part 1 (elixir part 6)
Phoenix Framework Tutorial Part 1 (elixir part 6)
Tensor Programming
37 Phoenix Framework Tutorial Part 2  (elixir part 7)
Phoenix Framework Tutorial Part 2 (elixir part 7)
Tensor Programming
38 Phoenix Framework Tutorial Part 3 (elixir part 8)
Phoenix Framework Tutorial Part 3 (elixir part 8)
Tensor Programming
39 A Intro to Clojure and Clojure Syntax
A Intro to Clojure and Clojure Syntax
Tensor Programming
40 An Update about the channel
An Update about the channel
Tensor Programming
41 Intro to Rustlang (Setup and Primitives)
Intro to Rustlang (Setup and Primitives)
Tensor Programming
42 Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Tensor Programming
43 Intro to Rustlang (Ownership and Borrowing)
Intro to Rustlang (Ownership and Borrowing)
Tensor Programming
44 Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Tensor Programming
45 Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Tensor Programming
46 Intro to RustLang (Enums and Options)
Intro to RustLang (Enums and Options)
Tensor Programming
47 Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Tensor Programming
48 Rustlang Project: Snake Game
Rustlang Project: Snake Game
Tensor Programming
49 Intro to Rustlang (Traits and Generic Types)
Intro to Rustlang (Traits and Generic Types)
Tensor Programming
50 Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Tensor Programming
51 Intro to Rust-lang (Modules and Lifetimes)
Intro to Rust-lang (Modules and Lifetimes)
Tensor Programming
52 Intro to Rust-lang (Macros and Metaprogramming)
Intro to Rust-lang (Macros and Metaprogramming)
Tensor Programming
Intro to Rust-lang (Error Handling)
Intro to Rust-lang (Error Handling)
Tensor Programming
54 Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Tensor Programming
55 Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Tensor Programming
56 Rustlang Project: Port Sniffer CLI
Rustlang Project: Port Sniffer CLI
Tensor Programming
57 Rustlang Project: Chat Application
Rustlang Project: Chat Application
Tensor Programming
58 Rustlang Project: CLI Toy Blockchain
Rustlang Project: CLI Toy Blockchain
Tensor Programming
59 Intro to Rust-lang (Setting up a Development Environment)
Intro to Rust-lang (Setting up a Development Environment)
Tensor Programming
60 Intro to Rust-lang (Building a Web API with Iron)
Intro to Rust-lang (Building a Web API with Iron)
Tensor Programming

This video teaches the basics of error handling in Rust using Result and Option Enums, and how to use the ? operator for concise error handling. It's essential for beginners in Rust programming to understand how to handle errors effectively.

Key Takeaways
  1. Set the global environment variable rust back-trace to 1
  2. Use the panic macro to force a panic in the program
  3. Use the exit function to panic if a certain condition is met
  4. Use a match statement to unwrap an Option enum
  5. Use Rust's Option type for error handling
  6. Use the Result enum for more nuanced error handling
  7. Use pattern matching to handle different cases
  8. Use the unwrap method to unwrap data or panic with an error message
  9. Use the expect method to panic with a custom error message
  10. Remove the top match block and make the F variable immutable and add a ? operator
💡 Rust's error handling system is based on the concept of Result and Error types, and is designed to prevent panics and crashes by treating errors as values.

Related Reads

📰
Neural Networks vs. Biological Neurons: A visual comparison of AI and the human brain.
Learn how neural networks compare to biological neurons and what AI can learn from the human brain
Medium · Data Science
📰
Conda Environment Naming: -n vs -p — Which One Should You Use?
Learn when to use -n vs -p for naming Conda environments and improve your workflow in Python, Data Science, and ML projects
Medium · Python
📰
Comparing Two Eval Runs by Their Average Pass Rate Is the Wrong Test
Comparing eval runs by average pass rate can be misleading, learn why and how to do it correctly
Dev.to · Maya Andersson
📰
ML Infrastructure vs. AI Infrastructure: Are They the Same Thing?
Learn the key differences between ML infrastructure and AI infrastructure to inform your tech strategy
Dev.to · Conor Breathnach
Up next
Arrays vs Lists: What AI Actually Prefers | Common Tech Interview Questions
SCALER
Watch →