Why You Need Custom Exception Classes

  Рет қаралды 18,160

ArjanCodes

ArjanCodes

Күн бұрын

In this video, I’ll show you how to create your own custom exception classes in Python. Stay tuned to find out why you should do that instead of just using the built-in system exceptions.
👷 Join the FREE Code Diagnosis Workshop to help you review code more effectively using my 3-Factor Diagnosis Framework: www.arjancodes.com/diagnosis
🔥 GitHub Repository: git.arjan.codes/2024/tuesday_...
💻 ArjanCodes Blog: www.arjancodes.com/blog
✍🏻 Take a quiz on this topic: www.learntail.com/quiz/mgzcmi
Try Learntail for FREE ➡️ www.learntail.com/
🎓 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:15 What are exceptions?
2:35 Custom exceptions in Python
4:24 How to use Exceptions
5:24 Summary
#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!

Пікірлер: 32
@ArjanCodes
@ArjanCodes 4 ай бұрын
👷 Join the FREE Code Diagnosis Workshop to help you review code more effectively using my 3-Factor Diagnosis Framework: www.arjancodes.com/diagnosis
@williamdroz6890
@williamdroz6890 4 ай бұрын
The video explains well the basics and why custom exceptions are useful. Since python 3.11, you can also add notes with "PEP 678 - Enriching Exceptions with Notes" and group them "PEP 654 - Exception Groups and except*".
@Piipolinoo
@Piipolinoo 4 ай бұрын
Did you actually give a reason why i need custom exception classes? I feel the basic ones get you a really long way
@Kaassap
@Kaassap 4 ай бұрын
Well you can extend the exception ___init___ method to make it do custom things on error and the added data. Can tidy up your code for a listener pattern.
@NickDanger3
@NickDanger3 4 ай бұрын
Excellent point: there is no information given on why I “need” custom exceptions. The example could easily have been handled with value error: the custom exceptions just added a lot of unnecessary code.
@endersteph
@endersteph 4 ай бұрын
​@@NickDanger3 I think besides customization the idea is that you have something more specific: You can catch specifically that error, and if that error is thrown it won't be catched by code checking for ValueError; therefore you have more control and less unexpected behavior.
@saminyead1233
@saminyead1233 4 ай бұрын
Well, I haven't yet watched Arjan's full video yet, but here's an example of why I use custom Exception class in a project of mine: I have a script that collects some data and pushes to a database. And I want to make sure that the data is pushed only once a day. In case the script needs to run twice, I want to prevent data being added twice to the database - so I implemented a custom TodayDataExistsError. It sort of raises the error like this: ``` if today_data_exists(): raise TodayDataExistsError("Today's data already exists") ``` Now, I could simply raise the built-in Exception with a custom message like so: ``` if today_data_exists(): raise Exception("Today's data already exists") ``` but for me there are several advantages to implementing this custom Exception: 1. When my script does run into the TodayDataExistsError, I would look at the console/logs and instantly "TodayDataExistsError" would jump out at me, and I would know exactly what's wrong in a jiffy. With the latter implementation, it would be a little harder for me (and thus would be ever so slightly more detrimental for my sanity) to find out exactly what's wrong - I would only see an Exception being raised, and only after reading the message, would I know what exactly is wrong. 2. As a developer of the code, the first implementation makes my life a lot easier than the second implementation. When I come back to my own code in a couple of months, I would inevitably have forgotten a lot of things about how my code works. When I see the TodayDataExistsError part, I can much easily figure out what my code is doing, than raising the built-in exception class. This makes refactoring much easier. 3. I could design my code around the custom Exception. For example, if there are a number of tables where different data needs to be pushed to, and if the script failed because it couldn't push to, say, the second table out of the three, then I could implement code that checks for the TodayDataExistsError, and if it is raised, move on to the next table skipping that: ``` for table in table_list: try: push_to_db() except TodayDataExistsError: continue ``` If I had only implemented the built-in exception, then I would have to but an Exception in the except block, which means, for whatever exception the code stops (not specifically because today's data already exists in the database), the iteration will be skipped.
@MatthijsRadeis
@MatthijsRadeis 4 ай бұрын
Really depends on the domain of application I guess. But he explicitly gives at least these two generic reasons: basic ones can be a bit cryptic and generic; and you can pass data through custom exceptions. Nothing groundbreaking, but nothing to vehemently disagree with either, it seems to me. Happy to hear otherwise.
@mikapeltokorpi7671
@mikapeltokorpi7671 4 ай бұрын
I had to find (by using logging module) which class method or function of multitude of classes and functions (and class methods) called the class that had a specific problem that did not throw an Exception when the said problem occured. This kind of approach worked brilliantly to solve that problem. Logging module and customized output formatting helped to get it also looking professional.
@WiktorWandachowicz
@WiktorWandachowicz 4 ай бұрын
In Java there IS a hierarchy of classes for error handling. First is *Throwable* which is inherited by *Exception* from which most of other CHECKED exception classes descend. There is also *RuntimeException* for UNCHECKED exceptions. Checked exceptions must be handled by "try-catch-finally" or specified as outgoing from a method by "throws", whereas unchecked exceptions might be thrown by any method without specifying them (like stack overflow, or out of memory errors). As much as I like Python and Arjan's explanations, please do not discredit Java when it is not necessary. Or please show examples side by side, if you really want to compare features of two programming languages. Thanks! PS. Exceptions handling in modern PHP is similar to Java, which is a compliment for the latter. So please remember to give credit where credit is due. Cheers!
@saryakan
@saryakan 4 ай бұрын
Yeah, I did a double take when he said you can throw any object and had to check since that threw me for a loop. I guess he came to that conclusion that, because Throwable instead of Exception is the base class.
@arcanjoaq
@arcanjoaq 4 ай бұрын
I think Arjan confused Java with JavaScript when he talked about the throwing of anything as an exception. JavaScript allows throwing a String, for example, as an "exception". :D
@saryakan
@saryakan 4 ай бұрын
@@arcanjoaq ah, the classic mistake
@adaum79
@adaum79 4 ай бұрын
So much content in so little time. Amazing, as always
@ArjanCodes
@ArjanCodes 4 ай бұрын
Glad you liked the video :)
@voidreamer
@voidreamer 4 ай бұрын
love these quick and clear ones, thank you
@ArjanCodes
@ArjanCodes 4 ай бұрын
I'm happy to hear you enjoy the content!
@askii3
@askii3 4 ай бұрын
KZbin: “ArjanCodes posted 42sec ago” Me: “Sweet!”
@Toopa88
@Toopa88 3 ай бұрын
What I don't get is in how far error handling should be used. I am working on a personal project and implement a REST API. At first I threw errors everywhere and handling status codes and error messages was painful. At some point I just established a "request state"-class with a data and error attributes (error: bool, status code, error message). So I check all functions that return such a state object by simply doing "if (state.error) {...}". Now I don't throw errors anymore since there's no need to. I have no idea if this is a bad approach but I feel like it made the code cleaner and easier to use.
@JoachimUngar
@JoachimUngar 4 ай бұрын
don't helium balloons have kind of a negative weight though?
@soklagenhet
@soklagenhet 4 ай бұрын
Not sure of adding business logic to exception init method. Just keep it simple - use custom exceptions with descriptive names, and make sure they work as ordinary, built in exceptions. Great for logging, e.g sentry.
@auroragb
@auroragb 4 ай бұрын
Personally, I think custom exceptions are only useful if you can code the exception condition inside. otherwise, standard ones work fine
@marcdelabarreraibardalet4754
@marcdelabarreraibardalet4754 4 ай бұрын
Why would you use finally if you can unindent the code? Its't it having the same behaviour?
@TigerWalts
@TigerWalts 4 ай бұрын
The except block may also raise an exception. The finally block will still be run in this case ensuring any clean up tasks are still run. Raising in a except block is usually done when you want to log the error but don't want to deal with it at that point in the code. Or you may want to raise it as a different exception type.
@praganesha.six-a8865
@praganesha.six-a8865 4 ай бұрын
Sir font name please?
@IvanIvanov-dk6sm
@IvanIvanov-dk6sm 4 ай бұрын
Hi, Arjan, thank you for the video. Could you please explain in one of future videos, when to use exceptions/errors and when to return None. I know that both of them should be used in proper scenarios, but the border of choosing is not that straightforward
@flam1ngicecream
@flam1ngicecream 4 ай бұрын
You should raise an Exception when something has gone wrong, your program has an invalid state, or the user has requested something nonsensical. Lost connection during a web request? Exception. Tried to divide by zero? Exception. Attempted to buy 5 tickets when there are only 3 left? Exception. Only return None when the thing the function is supposed to return is truly optional, and it's valid for the thing the user is requesting to not exist.
7 Python Code Smells: Olfactory Offenses To Avoid At All Costs
22:10
The Ultimate Guide to Writing Classes in Python
25:39
ArjanCodes
Рет қаралды 108 М.
What it feels like cleaning up after a toddler.
00:40
Daniel LaBelle
Рет қаралды 75 МЛН
Женская драка в Кызылорде
00:53
AIRAN
Рет қаралды 402 М.
Java Custom Exceptions Tutorial - It's Way Easier Than You Think
14:29
Coding with John
Рет қаралды 151 М.
Python 3.12 Generic Types Explained
18:27
ArjanCodes
Рет қаралды 59 М.
Protocols vs ABCs in Python - When to Use Which One?
15:31
ArjanCodes
Рет қаралды 33 М.
What the Heck Are Monads?!
21:08
ArjanCodes
Рет қаралды 69 М.
Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
19:09
ArjanCodes
Рет қаралды 288 М.
The State Design Pattern in Python Explained
19:14
ArjanCodes
Рет қаралды 73 М.
100+ Linux Things you Need to Know
12:23
Fireship
Рет қаралды 860 М.
15 Python Libraries You Should Know About
14:54
ArjanCodes
Рет қаралды 375 М.
Python's 5 Worst Features
19:44
Indently
Рет қаралды 104 М.
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 282 М.