Тёмный

Exception Handling Tips in Python ⚠ Write Better Python Code Part 7 

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

This video covers exception handling in Python and it gives you a few more advanced tips of how to handle exceptions in production environments, including using different exceptions at each level of your application, using a context manager to automatically clean up resources such as an open database connection, and using decorators to have an easy mechanism for retrying operations if an exception occurs, or automatically logging exceptions to a file.
After watching this video, make sure to watch my follow-up video that clarifies a few things from this video and also talks about another alternative for error handling: • Monadic Error Handling... .
💡Here's my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
Relevant books:
- Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides: amzn.to/3jllgyH
- Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development, by Craig Larman: amzn.to/364wgLb
- Principles of Package Design: Creating Reusable Software Components by Matthias Noback: amzn.to/2NETK3l
- Clean Code: A Handbook of Agile Software Craftsmanship by Robert Martin: amzn.to/3qVZgNs
- The original Design Principles and Design Patterns article by Robert Martin: fi.ort.edu.uy/innovaportal/fi... Courses:
The Software Designer Mindset: www.arjancodes.com/mindset
The Software Designer Mindset Team Packages: www.arjancodes.com/sas
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.
All parts in this series:
Part 1: Cohesion and coupling - • Cohesion and Coupling:...
Part 2: Dependency inversion - • Dependency Inversion: ...
Part 3: The strategy pattern - • The Strategy Pattern: ...
Part 4: The observer pattern - • Observer Pattern Tutor...
Part 5: Unit testing and code coverage - • 100% CODE COVERAGE - T...
Part 6: Template method and bridge - • Two UNDERRATED Design ...
Part 7: Exception handling - • Exception Handling Tip...
Part 7b: Monadic error handling - • Monadic Error Handling...
Part 8: Software architecture - • Why You Should Think A...
Part 9: SOLID principles - • Uncle Bob’s SOLID Prin...
Part 10: Object creation patterns - • QUESTIONABLE Object Cr...
You can find the code I worked on in this episode in my GitHub repository: github.com/arjancodes/betterp...
🔖 Chapters:
0:00 Intro
1:43 Example explanation
4:29 Running the example
5:59 Exception types and handling exceptions on different levels
12:43 Adding a context manager
16:12 Retry decorator
17:46 Automatic logging of exceptions
18:37 Disadvantages of handling errors by exceptions
19:47 Alternative ways of handling errors
21:20 Outro
👍 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!
🏆 Join my Discord server: discord.arjan.codes
👥Twitter: / arjancodes
👥LinkedIn: / arjancodes
👥Facebook: / arjancodes
#arjancodes #softwaredesign #exceptionhandling
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

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 197   
@DanT0007
@DanT0007 3 года назад
Been a solo developer at work for a couple years and these are the exact type of tutorials I need.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Dan, happy you're enjoying the videos.
@MaBuSt
@MaBuSt 2 года назад
I understand you completely.
@vfvermeers6259
@vfvermeers6259 2 года назад
I second this! As a solo developer this is a great guideline and resource to further my own experience and knowledge. Thank you Arjan!
@princeroshan4105
@princeroshan4105 Год назад
I can feel you 😬
@kevinjerome5954
@kevinjerome5954 Год назад
Great video! One consideration for other watchers: In some use cases, sending a 403 error back to the user is not always best practice. In terms of security, returning a 403 error tells a bad actor that private data definitely exists at that exact ID in your database. If you have security concerns about this (i.e. a brute force attack to undercover private blogs) you should just return a generic 404 error instead so that non-existent blogs and private blogs are indistinguishable to an attacker.
@joshuamcdonald5850
@joshuamcdonald5850 3 года назад
Man, these videos are really well made, well paced, and the content/expertise is top tier
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, Joshua, happy you enjoy them!
@gybsjskkddnnd3961
@gybsjskkddnnd3961 2 года назад
ID 2247524951
@nickscott9832
@nickscott9832 2 года назад
One thing I'd recommend is to add the top level route try excepts into a single decorator, and then reuse that decorator on each route. It really helps to reduce duplicate code and allows the function in the route to mainly be about the logic involved.
@murghay01
@murghay01 3 года назад
Love it, man. I'm too addicted to these videos. Still want to say - Appreciate the detailed videos. Hope you find joy doing these. Also, be my private mentor. :D
@ArjanCodes
@ArjanCodes 3 года назад
Thanks Gamal! I don’t do private mentoring but if I ever decide to start doing that, you’ll be the first to know ;)
@zarblitz
@zarblitz 2 года назад
Not doing anything with Python currently but I still love watching your videos since the concepts and ideas are generally applicable to programming. That said, having used a bit of Rust and Elm recently, I do appreciate being forced to reconcile errors. It slows you down a bit, sure, but help me to consider cases I might have glossed over in other languages. Having a Result type has really grown on me.
@mauisam1
@mauisam1 2 года назад
Fantastic Arjan, thank you for helping me understand exceptions and writing better code! I did not know about the finally: of a try block or that you could have two exceptions in one try block. I'm sure this sort of thing is in the docs but I learn better by doing/examples than by reading docs. So please keep up the great work, it's much appreciated!
@solarcide
@solarcide 3 года назад
Am pleased that your channel exists! Echoing many of the other connectors. Thank you for your continuing series designed to offer the dev a chance at implementing good dev practices. Python being one example language, many of the example videos' spirit applies to other languages. The videos have great pacing - good, simple modern example use cases to examine the neat of a topic.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, @solarcide - happy you are enjoying the videos!
@brianhacker7346
@brianhacker7346 3 года назад
Another easy to follow video that covered an advanced topic. I like how you show the initial code, review how it may not be ideal, than show the improvements made as you explain the topic. Excellent viewer count for the first day -- you have a following. Congratulations and thanks for your time.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Brian, happy you’re enjoying it. And indeed, definitely a lot of views within a single day!
3 года назад
04:09 Eek, don't teach people to use string formatting to create a database query! Especially when your ID is a string, this is a very bad habit to pick up. Use `?` placeholders instead, and let the database interface handle the substitution.
@ArjanCodes
@ArjanCodes 3 года назад
Agreed, this was an oversight. It’s already fixed in the Git repository.
@12valmirjr
@12valmirjr 3 года назад
Thank you very much for this series, it's so clean and to the point. Really high quality!!
@ArjanCodes
@ArjanCodes 3 года назад
Glad you like them!
@michaeldebetaz
@michaeldebetaz 2 года назад
8:50 - Hi Arjan and thanks for the video :) A VERY important note that is not addressed at this point: you are using string interpolation to make your SQL query , which make it vulnerable to SQL injection attacks ☝ The sqlite3 documentation mention it explicitly: use placeholder if you want to dynamically write your SQL queries. I don't know if you speak about that later, but I would recommend to mention that at first, for the viewers who don't watch the video until the end. In your example, it would be possible to delete all your blogs just by typing some query in the url endpoint. Please let me know if I'm wrong 👍
@michaeldebetaz
@michaeldebetaz 2 года назад
Ah well, you speak about that in the next video ^^ Too bad that RU-vid doesn't give a way to add some erratum to uploaded videos.
@ArjanCodes
@ArjanCodes 2 года назад
Yep, unfortunately there’s no easy way to do that other that refer to it in the description.
@vman2kay
@vman2kay Год назад
The video is focusing more on exceptions and how to handle them better. The code is just an example so people shouldn't take it as best practice. What you're referring to is parameterised queries. I guess new programmers might see that and try it but from watching a few I think Arjan's videos expect you to have some programming experience.
@cetilly
@cetilly 3 года назад
Your presentation style is fantastic. I really love the way you present the material as if we are sitting in the chair right next to you; makes the material really relatable. The retry decorator is a gem, so thanks for bringing that up because I have a Twitter bot that regularly loses its stream connection and this may be a great way to handle reconnects. Thanks Arjan.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Chuck. I’m happy that’s how you’re experiencing it, because I still have trouble behaving naturally when looking straight into a camera lens, haha. It’s a work in progress :).
@-bjorn-5465
@-bjorn-5465 3 года назад
So much fun to see that the contents of the SOM course are also touched in these videos! They are really helpful for my own projects :) Thanks Arjan!
@ArjanCodes
@ArjanCodes 3 года назад
Thanks Björn, glad you like the videos!
@lautaroleonhardt2600
@lautaroleonhardt2600 2 года назад
I'm improving my programming skills and gaining a deeper understanding of Python thanks to you!
@tombmyst11
@tombmyst11 2 года назад
The retry decorator is really great, thanks a lot! And thanks for the videos, a lot helpful, I do really appreciate the way you show things, not boring, not precise or redundant like a lot of resources found on the webzzz. 🍻
@MaBuSt
@MaBuSt 2 года назад
I know it is a silly distinction, but one of the great things about this video is how you keep things to very simple subsets of the use cases. SO many other videos would have called out to some database with a huge amount of data in there and we would have no idea the actual structure of what we are querying. Now, in general, you shouldn't need to know all the rows that are there and that's not the biggest of deals (in the real world)... however... when you are trying to think carefully about how to think (which is the case with your videos), you want to be able to wrap your mind around the entire concept and you creating a DB here with just 2 entries is gold.
@jumaxeno5004
@jumaxeno5004 9 месяцев назад
thank you Arjan ! please keep making videos. They are very inciteful
@vikas416
@vikas416 Год назад
Quite helpful discourse on error handling. The logger decorator is cherry on top. It's going to help quite a lot with logging
@malteplath
@malteplath 2 года назад
I like your videos. Well paced, very informative and well explained. I usually find one or two things that I would do differently, but not in this one! I will definitely recommend this to my colleagues.
@yjallan
@yjallan 2 года назад
man these videos are so freaking good in all kinds of ways! good job Arjan
@ArjanCodes
@ArjanCodes 2 года назад
Thank you so much - glad you like them!
@chrysolite13
@chrysolite13 3 года назад
Nice video. Very easy to follow, and I especially enjoyed the discussion of different error handling paradimes at the end.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, Chris!
@janHodle
@janHodle 2 года назад
Thank you! This is really helpful. Unfortunately in my role as a Data Architect/Data Engineer I have to write a lot of python code without having the possibility to challenge my code with other co-workers. These videos show me where I can improve my code to make it more reliable, more readable and avoid as much coupling and coherence as possible. THANK YOU SO MUCH!
@mr.madness7721
@mr.madness7721 11 месяцев назад
Amazing tutorial! I learned a lot. Thank you for creating it.
@cosmicblack
@cosmicblack Год назад
Nice video 2 years but still very useful , as always thanks for your time :)
@seattleshane569
@seattleshane569 3 года назад
Thank you for describing how to handle exceptions in such a logical way. I have struggled with this is exact issue when writing hardware modules that communicate with internet connected devices.
@ArjanCodes
@ArjanCodes 3 года назад
Glad it was helpful, Shane!
@CharleswoodSpudzyofficial
@CharleswoodSpudzyofficial 2 года назад
You are my new favorite channel for coding! I'm subbed!
@ArjanCodes
@ArjanCodes 2 года назад
Thanks so much Charles, and welcome onboard ;).
@FabioKasper
@FabioKasper 2 года назад
Woow, that context manager for a database connection. Learned something new today. Good stuff. Thanks!
@ArjanCodes
@ArjanCodes 2 года назад
Glad it was helpful, Fabio!
@joegaffney8006
@joegaffney8006 3 года назад
Nice one. From your retry decorator. I finally know how to properly pass optional arguments to decorators using double wrap of the decorator. This has saved some code duplication for me. Cheers.
@ArjanCodes
@ArjanCodes 3 года назад
Thanks a lot, Joe - glad it helped you 😊
@ArjanCodes
@ArjanCodes 3 года назад
This video was a bit longer than usual - I had a lot to cover, even after cutting out several minutes of my rambling :) Also check out my video about loops in Python if you like the discussion about programming languages features and why they exist: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-X0DBP5pxJ_8.html.
@danielellis6094
@danielellis6094 3 года назад
This video is great! I taught myself Python so I look to channels like yours to help me bridge learned theory into practical application. Cheers
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Daniel, glad you enjoyed the video. If you have any suggestions for topics, please let me know.
@BillusTinnus
@BillusTinnus Год назад
Wow, this video is very high quality. Thanks
@pranabsg
@pranabsg 2 года назад
Thanks Arjan for creating these best of the class videos!!! I became fan. Would be waiting to see best practices for Async way of handling Database/File operation.
@ArjanCodes
@ArjanCodes 2 года назад
Thanks for the suggestions, Pranab, and glad you enjoy the videos!
@raccoonteachesyou
@raccoonteachesyou 3 года назад
Great video ! Thank you for doing these !
@ArjanCodes
@ArjanCodes 3 года назад
Glad you like them, @Raccoon Teaches You !
@MagnusAnand
@MagnusAnand 2 года назад
Dude, AMAZING tutorial. Really amazing.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you - glad that you liked it!
@zetowaw
@zetowaw 2 года назад
Hi, I’m from Costa Rica and I’m learning python right now, your videos have been really helpful, thanks for the great content. Keep the good work 👍🏻
@ArjanCodes
@ArjanCodes 2 года назад
Hi! Glad to hear the videos are helpful to you!
@shashishekhar----
@shashishekhar---- Год назад
Thankful for you Arjan, god bless you and much appreciated from an up and coming developer.
@ArjanCodes
@ArjanCodes Год назад
Thanks Sakshi. Glad that you liked it.
@cs3705
@cs3705 3 года назад
Also solo devops at my job, this video was a good overview/refresher for exception handlers and context management. Cheers!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you!
@chriskeo392
@chriskeo392 3 года назад
Me too man lol Solo devops at my company is slowly turning me into a full stack engineer
@mohammedkhalid9317
@mohammedkhalid9317 2 года назад
Thanks Arjan, content is really helpful
2 года назад
Very clear explanation of the different possibilities to treat errors. Personally I think that error handling must solve the problem and return to a "well known workflow" as soon as possible. That is, the lower level methods should treat exceptions at their level and avoid raising errors up to their callers. I usually make my methods return some kind of "simple and agreed error status" when possible, but not step up raising exceptions. And this also lets me create few or even no custom error classes at all.
@SamuelTaylorUK
@SamuelTaylorUK 3 года назад
Great video! Love to see a video on documenting code.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, Samuel! That goes on my list 😊
@joaodiasconde
@joaodiasconde 2 года назад
Rust's approach with an enum type Result::(Ok|Err) is by far the best. The control flow is not affected, and the compiler forces you to use/unwrap your value. I think Scala also has this but with different names.
@benatakaan613
@benatakaan613 Год назад
Your content is amazing!!! Thank you for sharing your expertise. It is super helpful!
@ArjanCodes
@ArjanCodes Год назад
You're so welcome!
@darshake1
@darshake1 2 года назад
I love you man. Your knowledge and explanations are par excellence. Hope your channel will grow from strength to strength. Thank you
@ArjanCodes
@ArjanCodes 2 года назад
You’re welcome, glad to hear you like the content!
@talhaamir9023
@talhaamir9023 3 года назад
Falling in love with this channel
@ArjanCodes
@ArjanCodes 3 года назад
Thanks!
@haristan1960
@haristan1960 2 года назад
thanks Arjan for making this series
@ArjanCodes
@ArjanCodes 2 года назад
You're welcome!
@jonathanheadley2729
@jonathanheadley2729 2 года назад
Please keep up the stellar work!
@ArjanCodes
@ArjanCodes 2 года назад
Thanks Jonathan, will do!
@johncrunk8038
@johncrunk8038 2 года назад
Errors have been around since the beginning of time. As an old, OLD, IBM programmer, I really appreciated the way that every error in a program had an "error number" and description that was published in the user manual. This meant that every ( known ) error could be tracked down and hopefully resolved. Since most of the programming of olden days was batch processing, it was a necessity to have the ABEND code to track down your problem. I realize this is overkill for most stuff today, but it would still be nice for every program to have a reference manual for those.
@petersteenkamp
@petersteenkamp 2 года назад
Funny, I absolutely hated the whole concept of "error numbers". File not found? And what file would that be referring to? Doesn't say, even though the interpreter clearly knew what file it was looking for at the moment the error occurred. Go figure it out yourself. The interpreter hiding behind a number while not giving the relevant information even though the relevant information (like the filename in this case) should be available, always felt sadistic to me.
@SuperRealhigh
@SuperRealhigh 2 года назад
Very informative ! I thank you sir!
@Khushpich
@Khushpich 3 года назад
My new favorite programming channel
@ArjanCodes
@ArjanCodes 3 года назад
Thanks so much! Glad you’re enjoying the content!
@gertjanvandenbroek1620
@gertjanvandenbroek1620 Год назад
I did not know that the 'finally' keyword also fires when an uncaught exception is raised. I kind of assumed that it only triggered when you handled exceptions. Glad I know that now thanks.
@ArjanCodes
@ArjanCodes Год назад
You're welcome, Gertjan! That "feature" of the finally keyword is very useful, because it will run the cleanup code regardless of whether there was an exception or not.
@MonaCodeLisa
@MonaCodeLisa 9 месяцев назад
now that's a cool video :) enjoyed watching, thank you
@ArjanCodes
@ArjanCodes 9 месяцев назад
Glad you enjoyed it :)
@djbroake9810
@djbroake9810 Год назад
awesome thank you, explained it clearly while showing examples.
@ArjanCodes
@ArjanCodes Год назад
Thanks so much, glad the content is helpful!
@jagdish1o1
@jagdish1o1 Год назад
You really know your stuff. Thanks for this.
@ArjanCodes
@ArjanCodes Год назад
Thanks so much Jagdish, glad the content is helpful!
@robertbrummayer4908
@robertbrummayer4908 2 года назад
Great job! I really enjoy your videos.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you very much, Robert!
@adjbutler
@adjbutler 2 года назад
Thank you for these vids. AMAZING! ☺
@ArjanCodes
@ArjanCodes 2 года назад
Glad you like them!
@whkoh7619
@whkoh7619 2 года назад
Amazing content. Thanks Arjan!
@ArjanCodes
@ArjanCodes 2 года назад
You’re welcome, glad you like it!
@mootaizaz6378
@mootaizaz6378 3 года назад
best channel for a python developer and software engineer in general
@ArjanCodes
@ArjanCodes 3 года назад
Thank you!
@ComputerScienceSimplified
@ComputerScienceSimplified 3 года назад
Awesome video, keep up the incredible work! :)
@ArjanCodes
@ArjanCodes 3 года назад
Thank you - will do ;)
@khalilrouatbi6345
@khalilrouatbi6345 2 года назад
thank you so much sir! this has been really helpful!
@ArjanCodes
@ArjanCodes 2 года назад
Glad it helped!
@mrswats
@mrswats 2 года назад
I really like the contextlib module from the standard library to create context managers with a function. One thing I do not like about context managers is that they can hide other unrelated errors if not properly set up. I had this problem once and I will never forget about it, but it's still tricky. Logging everything helps a lot when debugging things like that.
@meh.7539
@meh.7539 2 года назад
As some one who hunts for vulnerabilities in my spare time, I can tell you that I **LOVE** poorly handled exceptions and stack traces. Just something to remember :)
@davido2513
@davido2513 2 года назад
The exception decorator is pretty slick
@ren9812
@ren9812 2 года назад
13:24 sqlite3 actually has a builtin support of context manager, sqlite3.connect() creates an objects with __enter__/__exit__ methods
@willTryAgainTmrw
@willTryAgainTmrw 3 года назад
great video. learnt about the part of python usually untouched by tutors.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Pratham, glad you like it!
@ondskabenselv
@ondskabenselv 3 года назад
I really enjoy your videos, thanks for making them! You mentioned using both REST and GraphQL; it would be nice to have a video using the same logic for both, contrasting their differences :)
@ArjanCodes
@ArjanCodes 3 года назад
Good idea, thank you!
@imajindevon
@imajindevon 2 года назад
Such a good video!
@ArjanCodes
@ArjanCodes 2 года назад
Thanks so much!
@naveenv3097
@naveenv3097 2 года назад
15:45 the horn , very funny :) LOL ... Great video, Thanks
@ArjanCodes
@ArjanCodes 2 года назад
You’re welcome ☺️
@SP-db6sh
@SP-db6sh 3 года назад
Better far better than udemy courses. Keep growing & sharing this way of creating sensible content.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you so much! And will do ;)
@abdelghafourfid8216
@abdelghafourfid8216 2 года назад
8:46 one other advantage of finally block over copy pasting the code inside execpt block, is that it garanties that the code within finally would be always executed, even, for example, if other exceptions are raised in your except block.
@TinBryn
@TinBryn 2 года назад
I approach error handling by avoiding it as much as possible. I try to make as much as my logic as error free as possible and pass the successful results of error handled code into them. For example I prefer having something take in a file than a file name. That way I only have to handle read and/or write errors and not file not found, lack permission errors, etc.
@zachary007
@zachary007 3 года назад
I'm a Python guy. Love your channel.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Zachary, glad you like it!
@andrewwhyte9329
@andrewwhyte9329 Год назад
Thank you! Exactly what I needed. Any optimizations for networking errors?
@syberen
@syberen 3 года назад
Excellent!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, Syberen!
@Amy-ve3ke
@Amy-ve3ke Год назад
Amazing work
@ArjanCodes
@ArjanCodes Год назад
Thanks Amy, Glad that you liked it.
@LoveisHell85
@LoveisHell85 3 года назад
Love the channel. Please make a video about structural design in python. How to make a large project that is clear and well structured. How to avoid function tunnels that need to deliver certain input to the bottom of the tunnel. For ex. creds to API call. I would also like to see ETL-videos. From API to process to database. Thank you!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, I’ll definitely consider those topics!
@LoveisHell85
@LoveisHell85 3 года назад
@@ArjanCodes thanks! Enjoy The weekend!
@plexq
@plexq 2 года назад
Scala/Haskell both use error Monads which are a more SOLID compliant way of doing error handling and avoiding pretty much all the pitfalls of errors. This is a solution I was hoping to see discussed. Sadly it was missed as the already common best way of handling errors in less basic languages than python.
@ArjanCodes
@ArjanCodes 2 года назад
I did a follow-up video to this one dedicated to Monadic error handling, see: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-J-HWmoTKhC8.html.
@yuriytigiev8816
@yuriytigiev8816 Год назад
I need your advice. I need to write a function that will check the free balance for the purchase of goods, and also if there are not enough funds, then wite a warning about this in the log file with a list of variables (balance, used balance and cost of the goods). I see two possible solutions - 1) the necessary check is made and if there are not enough funds, then display a warning and return the value False. 2) the necessary check is made and if there are not enough funds, then call a custom exception with a list of necessary variables, and in the external function implement the exception catching and writing to the log. The question is which of the two options is preferable or share a more correct option.
@manonthedollar
@manonthedollar 3 года назад
8:50 - What about the case where sqlite throws an exception when trying to connect during line 37 (con = sqlite3.connect), and so the `con` variable is never assigned. Would placing the `con.close()` in a `finally` block throw an additional, unhandled exception? I LOVE your videos and am learning a TON. Thank you!!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you and well spotted! I actually fixed this in last week’s video, where I check in the leave method of the context manager whether the conn variable actually contains a value.
@manonthedollar
@manonthedollar 3 года назад
@@ArjanCodes Aha! Watching this right now! Thanks once again for EVERYTHING!
@kosmonautofficial296
@kosmonautofficial296 2 года назад
Great video thanks. I am still trying to figure out when to use if else and check for the thing that causes the error rather than try except. I have mainly been doing if else such as checking if a file exists first, then checking I have permissions to view it, then that it is not already opened. It sounds like this could be something I add to my rest api calls in the code to handle a connection error because I am not sure how to do that with if else.
@programminginterviewsprepa7710
You can also do like return Try(something) like in crazy scala
@snoopyjc
@snoopyjc 2 года назад
You need to put a try: block around your close() else if the DB was never opened (open failed) the close will raise an exception
@ivanherreros7773
@ivanherreros7773 2 года назад
Really good.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Ivan!
@andreo4081
@andreo4081 2 года назад
Just seen a video from uncle Bob where he mentioned that the only thing he wants to see in a 'try' block is the one line of code calling the function/method...
@sushantrocks
@sushantrocks 2 года назад
Great stuff
@ArjanCodes
@ArjanCodes 2 года назад
Thank you!
@sushantrocks
@sushantrocks 2 года назад
@@ArjanCodes I always find it hard to decide where to log the exception, where to consume it and where to raise. I found what works is to first decide and define the exceptions for the module. Then make sure the public methods return those only. Private methods do the logging and raise what they want.
@markblacket8900
@markblacket8900 2 года назад
wait a second, base class for every exception is BaseException, SystemExit and KeyboardInterrupt are inheriting from it, not from the usual Exception so it won't get caught by generic "except Exception" handlers (source: python 3 docs)
@beijingdiaries
@beijingdiaries 2 года назад
When would be the next movie coming out of the 'MUMMY' series? This guys really seems the lead actor :P
@neotodsoltani5902
@neotodsoltani5902 3 года назад
Why not make a db connection at the beginning when we run the web server, and then close it when we end the webserver or an exception occurred? Is that for security reasons?
@ArjanCodes
@ArjanCodes 3 года назад
In a production environment, that would definitely be the way to go. In that case you’d probably not use SQLite either, but connect to a database server instead. In this video, I wanted to keep things simple and focus on the resource cleanup part together with exceptions, that’s why I incorporated creating the connection inside each API function. I’ll perhaps do another video series where I focus on setting up a backend API with everything surrounding that.
@-bjorn-5465
@-bjorn-5465 3 года назад
@@ArjanCodes Looking forward to that video!
@javier232010gmail
@javier232010gmail 2 года назад
16:00 Lol. Great video
@ArjanCodes
@ArjanCodes 2 года назад
Thanks!
@AnIceCrasher
@AnIceCrasher 3 года назад
Thank you :D Could you make a video, especially about dependancy injection - for example if you want to inject a specific, already existing class. So where to create this class that then is injected in possibly multiple other classes.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you and great suggestion, @IceCrasher! This video talks about a variation of what you're suggesting: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Kv5jhbSkqLE.html. I'll definitely also consider doing a more in-depth dependency injection video.
@AnIceCrasher
@AnIceCrasher 3 года назад
@@ArjanCodes Thank you. I have already watched that video. If you’d make a more in-depth video, it would be terrific - I like very much your style of explaining things. Maybe a video, where you also take factories into account. A wonderful example could be if you want to read a config file, where your lamps at home are defined. Then all the lamps in this config file must be created. Afterward, the lamps need to be injected into multiple other classes. For example, in a Home_automation class (that is able to switch them on and off) as well as into a House_cleaning_scheduler (that tells you when to clean your lamps). It also would be very interesting, how you would organize all these classes and interfaces in your file hierarchy. Anyway, keep up the good work. :)
@ArjanCodes
@ArjanCodes 3 года назад
Thank you @IceCrasher, will keep this in mind for my planning!
@guocity
@guocity Месяц назад
Can you use just "except e" to catch all exceptions? If so, what are the implications of doing that?
@dorb1337
@dorb1337 2 года назад
I need more.
@ArjanCodes
@ArjanCodes 2 года назад
Working on it ;)
@mathmo
@mathmo 2 года назад
Would the "finally" clause really ever be executed if no exception is thrown in the try block (because of the return statement)? I would have thought that if no exception occurs def fun(): try: do_something() return some_value except: do_something_else() finally: do_yet_another_thing() is equivalent to def fun(): do_something() return some_value do_yet_another_thing() which in turn is equivalent to def fun(): do_something() return some_value
@rafy-ivanmorales3077
@rafy-ivanmorales3077 2 года назад
I’m a new student and need help to do this project: I have a port scanner script it works properly; it works in Pycharm using python3.9. I have to make a file and I call this file (Example.txt). On this example file, I have to do this: 3. If the Ports is open, it should create a file and add an entry for port number 4. In case of any exception for instance “host is not available”, “host name could not be resolved” or due to any other error, you need to write that exception into the same file. I’m not asking for you to do the project for me, I'm only asking ware I need to work or used in my script to accomplish this because it is my first time doing this and working with python too, and I have been struggling with this part one very bad. I can even send you the code, so you can look and only tell me what I’m doing bad and is not working. Or try to make one day a video about this because I have search for this subject and I have not seen anything showing how to do these things in a script.
@khushaltrivedi9829
@khushaltrivedi9829 Год назад
raise exception vs return mesaages what wud u prefer ?
@BrianOSheaPlus
@BrianOSheaPlus 2 года назад
Great video. Side note: you type so fast! Are you speeding up the video over the times that you are typing to save time, or are you just an insanely fast typist?
@ArjanCodes
@ArjanCodes 2 года назад
Thanks Brian. I'm a horribly slow typer actually, haha. I speed those parts up to not make you endure that :).
@BrianOSheaPlus
@BrianOSheaPlus 2 года назад
@@ArjanCodes hahaha, thanks. Now I don't feel so slow! 🤪
@michaelcorvin1129
@michaelcorvin1129 2 года назад
@@ArjanCodes LOL! I had a close friend and colleague who actually did type that fast - and hard. She always had a spare keyboard ready for when she broke the one she was using!! And when she was typing code that fast she was so immersed that you could have a brief conversations with her which she wouldn't remember afterwards. Brilliant, talented person. Hearing your 'fast forward' typing in the first video of yours I watched reminded me of her. RIP Allison.
@evilwizard7931
@evilwizard7931 2 года назад
How would the fetch_blog work if there was a context manager used with the sqllite? I've heard it's a code smell to manually close things. Thanks, I should have just watched & waited before asking.
@TheRich107
@TheRich107 2 года назад
Great video, what keyboard are you using ?
@ArjanCodes
@ArjanCodes 2 года назад
Thanks Richard! I'm using a Keychron K2.
@anjalikshirsagar5714
@anjalikshirsagar5714 2 года назад
some dat file i want to to read it in excel column wise by using python code
@barciewicz
@barciewicz Год назад
Shouldn't the "blog_lst_to_json" function be called one level above, in API routes? For me it seems like a high-level consideration how data is serialized, and also "json"-related stuff seems to belong to HTTP domain.
Далее
15 Python Libraries You Should Know About
14:54
Просмотров 368 тыс.
220 volts ⚡️
00:16
Просмотров 702 тыс.
Do We Still Need Dataclasses? // PYDANTIC Tutorial
16:33
Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
26:14
Advanced Exception Handling in Python
12:06
Просмотров 55 тыс.