Why You Need Custom Exception Classes

  Рет қаралды 21,098

ArjanCodes

ArjanCodes

Күн бұрын

Пікірлер: 32
@ArjanCodes
@ArjanCodes 10 ай бұрын
👷 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 10 ай бұрын
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 10 ай бұрын
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 10 ай бұрын
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 10 ай бұрын
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 10 ай бұрын
​@@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 10 ай бұрын
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 10 ай бұрын
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 10 ай бұрын
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.
@adaum79
@adaum79 10 ай бұрын
So much content in so little time. Amazing, as always
@ArjanCodes
@ArjanCodes 10 ай бұрын
Glad you liked the video :)
@WiktorWandachowicz
@WiktorWandachowicz 10 ай бұрын
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 10 ай бұрын
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 10 ай бұрын
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 10 ай бұрын
@@arcanjoaq ah, the classic mistake
@Toopa88
@Toopa88 9 ай бұрын
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.
@voidreamer
@voidreamer 10 ай бұрын
love these quick and clear ones, thank you
@ArjanCodes
@ArjanCodes 10 ай бұрын
I'm happy to hear you enjoy the content!
@JoachimUngar
@JoachimUngar 10 ай бұрын
don't helium balloons have kind of a negative weight though?
@praganesha.six-a8865
@praganesha.six-a8865 10 ай бұрын
Sir font name please?
@marcdelabarreraibardalet4754
@marcdelabarreraibardalet4754 10 ай бұрын
Why would you use finally if you can unindent the code? Its't it having the same behaviour?
@TigerWalts
@TigerWalts 10 ай бұрын
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.
@askii3
@askii3 10 ай бұрын
KZbin: “ArjanCodes posted 42sec ago” Me: “Sweet!”
@soklagenhet
@soklagenhet 10 ай бұрын
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.
@IvanIvanov-dk6sm
@IvanIvanov-dk6sm 10 ай бұрын
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 10 ай бұрын
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.
@auroragb
@auroragb 10 ай бұрын
Personally, I think custom exceptions are only useful if you can code the exception condition inside. otherwise, standard ones work fine
This Is Why Python Data Classes Are Awesome
22:19
ArjanCodes
Рет қаралды 823 М.
Advanced Exception Handling in Python
12:06
NeuralNine
Рет қаралды 69 М.
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 958 М.
人是不能做到吗?#火影忍者 #家人  #佐助
00:20
火影忍者一家
Рет қаралды 20 МЛН
How Senior Programmers ACTUALLY Write Code
13:37
Thriving Technologist
Рет қаралды 1,6 МЛН
Real 10x Programmers Are SLOW To Write Code
14:51
Thriving Technologist
Рет қаралды 71 М.
The Ultimate Guide to Writing Classes in Python
25:39
ArjanCodes
Рет қаралды 124 М.
Dependency INVERSION vs Dependency INJECTION in Python
17:51
ArjanCodes
Рет қаралды 164 М.
7 Python Code Smells to AVOID at All Costs
22:10
ArjanCodes
Рет қаралды 377 М.
The Absolute Best Intro to Monads For Software Engineers
15:12
Studying With Alex
Рет қаралды 680 М.
7 Functional Programming Techniques EVERY Developer Should Know
21:35
My FAVORITE Error Handling Technique
16:01
ArjanCodes
Рет қаралды 47 М.
__new__ vs __init__ in Python
10:50
mCoding
Рет қаралды 211 М.