Тёмный

Rust Handles Errors Way Better Than Python 

ArjanCodes
Подписаться 239 тыс.
Просмотров 17 тыс.
50% 1

In this video, I’ll show you how Rust handles errors and when to use which type of error handling, based on my own experience.
🔥 GitHub Repository: git.arjan.codes/2024/rust_err...
💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
💻 ArjanCodes Blog: www.arjancodes.com/blog
✍🏻 Take a quiz on this topic: www.learntail.com/quiz/apifir
🎓 Courses:
The Software Designer Mindset: www.arjancodes.com/mindset
The Software Architect Mindset: Pre-register now! www.arjancodes.com/architect
Next Level Python: Become a Python Expert: www.arjancodes.com/next-level...
The 30-Day Design Challenge: www.arjancodes.com/30ddc
🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes.
👍 If you enjoyed this content, give this video a like. If you want to watch more of my upcoming videos, consider subscribing to my channel!
Social channels:
💬 Discord: discord.arjan.codes
🐦Twitter: / arjancodes
🌍LinkedIn: / arjancodes
🕵Facebook: / arjancodes
📱Instagram: / arjancodes
♪ Tiktok: / arjancodes
👀 Code reviewers:
- Yoriz
- Ryan Laursen
- Dale Hagglund
- Kit Hygh
- Alexander Milden
- Bean
🎥 Video edited by Mark Bacskai: / bacskaimark
🔖 Chapters:
0:00 Intro
0:48 Error handling in Python
3:36 Understanding Rust's Error Handling Paradigm
5:40 The Power of match
7:37 Error Handling with the ? Operator
12:11 Unwrapping Errors: panic!, unwrap and expect
16:05 Final Thoughts
17:37 Outro
#arjancodes #softwaredesign #python
DISCLAIMER - The links in this description might be affiliate links. If you purchase a product or service through one of those links, I may receive a small commission. There is no additional charge to you. Thanks for supporting my channel so I can continue to provide you with free content each week!

Опубликовано:

 

29 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 58   
@ArjanCodes
@ArjanCodes Месяц назад
💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
@Floatharr
@Floatharr 2 месяца назад
I recently learned Rust as a Python user, and I've been really enjoying the extra clarity the language provides, and how it allows me to make better decisions about how my program works. Very happy to see more Rust content!
@AhmedIsam
@AhmedIsam 2 месяца назад
Hint: you can use Result type in python as 3-rd party library. What matters is, porting over the concept.
@ArjanCodes
@ArjanCodes 2 месяца назад
I'm glad you're enjoying this type of content!
@martimlobao
@martimlobao 2 месяца назад
You mentioned the returns package, do you think you could make a video on how it works?
@danielmelo389
@danielmelo389 2 месяца назад
The problem with python error handling is that it's too prone to be abused, and quite frequently it is
@houstonbova3136
@houstonbova3136 2 месяца назад
I feel this is the case in most programming languages. I'd more say it as. The thing that makes Rust error handling great is that its nearly impossible to abuse and enables refactoring for better error messages to be really easy.
@diegol_116
@diegol_116 2 месяца назад
I really like what Go did along the same lines of handling errors explicitly... but I must admit that Rust seems to handle it better
@TheEvertw
@TheEvertw 2 месяца назад
I LOVE Rust. I also LOVE Python. And I think the two complement each other marvelously. It is very easy to write Python modules in Rust.
@saitaro
@saitaro Месяц назад
How does that work, Python types translate to those of Rust, like list to Vector or smth? Or there're types which emulate Python ones?
@SiricioHernandez
@SiricioHernandez 2 месяца назад
As Python developers (accustomed to unexpected errors, sometimes in production) to find Rust (a language with which you can feel confident when deploying) is like finding a piece of candy. Rust is complicated. It's not as widespread or has as many libraries as Python by far, but it's solid as a rock. I've been studying it, and my conclusion is that it's as solid as they say, but by-no-way-near has the ease of use that Python offers. Example: In Rust, Errors are types, so at the end, you need to use a "kind of Error wrapper" (like thiserror) to manage them. Solid and efficient, but complex. After fighting with Axum and some cryptic error messages (see decrusting Axum by Jon Gjengset), I've left Rust and jumped to Go to give it a try. That's because I think Go it's a good middle ground between the ease of Python and the robustness of Rust, but we'll see what happens. By now, I am getting good feelings. Sorry to say this, Arjan, but I think that, at some point, Rust builds a hard-to-tear-down-wall for Python developers.
@saitaro
@saitaro Месяц назад
Do you consider Go to complement Python better for webdev than Rust?
@matheusaugustodasilvasanto3171
@matheusaugustodasilvasanto3171 2 месяца назад
Rust's type system is truly a treat. I find myself trying to emulate it often in python, with result type hierarchies and frequent type checks, instead of relying on exceptions to propagate signals. However, a downside of this approach is the need to wrap almost all third-party code with type hints indicating what errors might emerge from their execution, which is not always easy, specially if the documentation is sparse. Thank God for context managers, they help a bit with that!
@OkayNoway
@OkayNoway 2 месяца назад
My colleague has been spamming me with rust propaganda, and now this. Do you have a beginners guide to rust? (from python background 😀) Also, thanks for the quality content Arjan!
@jiddick
@jiddick 2 месяца назад
ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-MoqtsYLGCC4.htmlsi=_bmleRmGPR9XdMfS
@Floatharr
@Floatharr 2 месяца назад
I highly recommend the free online book The Rust Programming Language, and the accompanying interactive exercises called "rustlings". I learned Rust from zero in about a week with those.
@itopaloglu83
@itopaloglu83 2 месяца назад
Can you please add "ignore dead code" macro in rust examples so that we can focus on the main content and not all the warnings?
@sebastianrossetti6167
@sebastianrossetti6167 2 месяца назад
Great video, as usual! Please do more videos on Rust. I've been trying to get into it for a bit but the syntax is a bit scary. For me, you make learning new things as easy as it can be. Thanks!
@AhmedIsam
@AhmedIsam 2 месяца назад
its a trade-off, you get explicit about everything, the result is scary. You impicitly assume a lot, the syntax is easy. People see maths proofs scary, but its actually extremely simple, jutst no hidden magic. You need to strike the right balance, and choose language that makes assumptions that you are happy with, e.g. float is float64 and I'm totally happy with it 99.99% of the time, I don't want any lower level details to be explicit in the langauge.
@sidward
@sidward 2 месяца назад
Hello! Love the video -- I have a small suggestion if you are open to it: when explaining a new language, it takes a second for someone like to understand the difference between a compiler error and co-pilot suggestion. Possibly skill issue :) but it would be nice to just see the compiler error and not worry about the other things suggested or recommended
@EngineerNick
@EngineerNick 2 месяца назад
I recently started using the anyhow crate, and it really steps up the experience to a whole new level of egonomics. Rust errors are fantastic untill you realise a function can only return a single result type. And then anyhow just makes that problem go away. Magic
@user-uc6wo1lc7t
@user-uc6wo1lc7t 28 дней назад
Isn't there some kind of error enums for this case? At least, in std::...::TcpListener when I handle a connection, there may be different kinds of errors.
@sdpayot
@sdpayot 2 месяца назад
Hi Arjan, for a "best of both worlds" solution, you might want to checkout the anyhow crate. it brings a little bit of extra-convenience to Rust's error handling framework by wrapping all kinds of errors into an anyhow::Error trait.
@JohnJohnson-dl8oq
@JohnJohnson-dl8oq Месяц назад
Would love to see your take on the returns package!
@NicolasChanCSY
@NicolasChanCSY 2 месяца назад
Hi Arjan. Thanks for the new video. The terminal output are often at the bottom of the screen in this video and thus are obscured by the closed captions. Can you please scroll down a bit and make it clearer to see? There are also code unrelated to the current section of the video, e.g. 13:37. Maybe you can hide/fold them or add a bunch of empty lines to them to make them out of sight for a moment?
@localhost0148
@localhost0148 Месяц назад
It was a really great and calm explanation. Thanks !
@ArjanCodes
@ArjanCodes 25 дней назад
Glad you enjoyed it!
@pudicio
@pudicio 2 месяца назад
Errors as values is very old. I think what is great in this example is that the Rust compiler helps you not have errors that aren't dealt with. But imho, it's a tradeoff between readability/boilerplate and safety. In python I can wrap a whole group of nested function calls in a try except block and have the rest of the code be very quick to read. But it's true that the onus is on the programmer to figure out what exceptions could be raised. I therefore like the Java like syntax of function XYZ raises A,B,C My main takeaway is it would be awesome to have some kind of static checker for python that checks which exceptions are unhandled.
@bloodgain
@bloodgain Месяц назад
Exception specifications are extremely painful without better result/optional support like what Rust offers. C++ almost went that route like Java, but wisely realized what is more important is specifying `noexcept` when a function _shouldn't_ throw. Exception specifiers are a major cause of interface changes, which should be minimized.
@Impolite6263
@Impolite6263 6 дней назад
thanks for this video man. i'm learning rust while writing pet project and result really bothered me until i found this video.
@ArjanCodes
@ArjanCodes 6 дней назад
Glad it helped!
@Aceptron
@Aceptron 2 месяца назад
I SEE RUST, I CLICK
@Optimusjf
@Optimusjf 2 месяца назад
Teacher, this content is excelent.
@ArjanCodes
@ArjanCodes Месяц назад
I'm glad you like it!
@charlescowart5423
@charlescowart5423 Месяц назад
I apologize I might be missing something but can’t you just look at the stack trace to figure out where it raised the error?
@_baco
@_baco 2 месяца назад
I wonder if in `read_file_if_exists` the Fail-Fast principle can be applied, returning `None` immediately if opening the file raised an error; or if it's too much boilerplate to re-struct that because of the `if-let` syntax natively provided in Rust. I mean, thinking out loud, I would have expected something like `if not Ok(my_file) .... blah, blah, blah... return None`; and then the code to continue de-indented assuming the file was open correctly. Not letting the fail return to be at the end.
@Betacak3
@Betacak3 2 месяца назад
Result has a method called ok() that turns the Result into an Option. You can use that on the Result returned by File::open(), then append a ? to return in case of a None. The same applies for file.read_to_string(). Here's how the function could also be written: let mut file = File::open(path).ok()?; let mut contents = String::new(); file.read_to_string(&mut contents).ok()?; Some(contents)
@Betacak3
@Betacak3 2 месяца назад
Alternatively, you could do this, which is more verbose but does pretty much the same (not including the entire function body this time): let mut file = match File::open(path) { Ok(f) => f, Err(_) => return None, };
@Whatthetrash
@Whatthetrash 2 месяца назад
I have found Rust to be too heavy in terms of mental overhead for practical problem solving (all I do is solve problems with Rust LOL). That said, I really like the idea of 'Result' and have started using it in Python (pip install result). I think it's cleaner and clearer than the 'Try-Except-Else-Finally' approach that's in Python. :)
@Forseti2
@Forseti2 2 месяца назад
How is that error handling better than in python? You can basically do the same with try-except, return tuple or other structure and add type hints for the result. The difference is that python will not enforce this (mypy could do this). But that's rather language property that python isn't so strict about types.
@imadetheuniverse4fun
@imadetheuniverse4fun 2 месяца назад
he went over that in the beginning, it's the fact that you can't tell what *type* of errors you're going to be handling in python, but you can in well-written rust.
@Forseti2
@Forseti2 2 месяца назад
@@imadetheuniverse4fun yeah, I've saw that and know from my daily python coding routine at job, but how is that different from the rust way? That's what I don't understand. When he demonstrated the rust way, the code just split into OK-result and Error-result (as with python try-except) - so how exactly is the rust better, when it's similarly generic as python? Let's not take rust strict typechecking into account - this is definitely berefit and I acknowledge that.
@lucianop.3922
@lucianop.3922 2 месяца назад
I totally agree with this. I get that typechecking is a huge plus for many and I can see how it helps readability but functionally speaking or even from an "amount of code" perspective I don't see that much of a difference. I mean, many programming language properties are there more for readability (which then helps in a lot of other areas like debugging, maintenance, etc. etc.) than for anything else like functional/timesaving, and if we are talking strictly functional, technically there's nothing that couldn't be coded using assembly or C, so under those lens, pretty much every programming language/tool out there "doesn't make much of a difference". But, still, I feel that sometimes this reasoning of "well if seen under those lens then nothing makes any difference" goes too far and there are features that really don't make that much of a difference. It's still cool though, don't get me wrong, personally I just don't like it when a feature is "sold" so to speak to do more than it actually does, because that creates confusions, that's my only concern really, not the fact that some people find it useful. If you find it useful, that's great.
@pandagoeshome
@pandagoeshome 2 месяца назад
Agree, he didn't catch any specific errors. He caught all errors it seems which is very easy to do in python. Or maybe I'm misunderstanding his point ...
@JohnJohnson-dl8oq
@JohnJohnson-dl8oq Месяц назад
Comments go a long way. A doc string for the (Python) function can include “Raises: ValueError”, etc.
@Tomlm6060
@Tomlm6060 2 месяца назад
What a thumbnail. I love it
@ArjanCodes
@ArjanCodes 2 месяца назад
Ahah! I'm glad you like it!
@jamesarthurkimbell
@jamesarthurkimbell 2 месяца назад
Sometimes I accidentally type "return ValueError" instead of "raise ValueError" and then I think "hmm, maybe that *would* be a better way..."
@Joao-pl6db
@Joao-pl6db 2 месяца назад
panic!("lol")
@DrSunRu
@DrSunRu 2 месяца назад
Learn returns library
@THEMithrandir09
@THEMithrandir09 2 месяца назад
Python is weird anyway, because usually exceptions are raised and errors are returned.
@diegosorte
@diegosorte 2 месяца назад
The first thing I thought was “is this an R video?????” 😅
@alejandroioio6784
@alejandroioio6784 2 месяца назад
You can use types, Although it doesn't make much sense to me to explicitly say this function can return a value and or an error, why would you return an error? that arrangement from my point of view leads to smelly code
@getcass
@getcass 2 месяца назад
Got to be said, rust syntax is mental.
@iklintsov
@iklintsov 2 месяца назад
No to curly brackets and semicolons
@yawninglion
@yawninglion 2 месяца назад
Is this a Rust channel now?
Далее
How to Avoid Dependency Hell in Programming
5:20
Просмотров 8 тыс.
Should You Use Dependency Injection Frameworks?
14:43
АСЛАН, АВИ, АНЯ
00:12
Просмотров 1,4 млн
5 Good Python Habits
17:35
Просмотров 400 тыс.
The State Design Pattern in Python Explained
19:14
Просмотров 72 тыс.
8 deadly mistakes beginner Rust developers make
14:14
Просмотров 157 тыс.
Deep Dive Into the Repository Design Pattern in Python
11:56
Rust: When C Code Isn't Enough
8:26
Просмотров 154 тыс.
err != nil Is GOOD? (And Why)
7:19
Просмотров 86 тыс.
25 nooby Python habits you need to ditch
9:12
Просмотров 1,7 млн
All Rust features explained
21:30
Просмотров 287 тыс.
Rust and RAII Memory Management - Computerphile
24:22
Просмотров 218 тыс.