Do you implement your own exception class in python ?
For now, I haven't encountered the situation I get in trouble
without original ones. I mean, built-in Exception is enough.
What would be the main benefit of self-implemented Exception ?
Generally, the only times you should be defining your own exceptions are when you have a specific case where raising a custom exception would be more appropriate than raising a existing Python exception.
For example, say I was implementing a command line argument parsing API, and I needed to account for the case where a user enters an invalid command line argument, whatever it may be. Now I could simply raise a Python exception like SyntaxError or a NameError, but that would be a bad design decision.
I want to be able to convey to the user why an exception is being raised, not just that an exception is being raised. A better option would be to subclass the general exception class Exception, and create a specific, custom exception. Perhaps InvalidCommandLineArgument.
Now instead of having to use a general Python exception, I can use my custom exception which helps to clearly and concisely inform the user of their error.
This can also be useful if you want to be informed when a certain action fails in your code. For instance, if you create a function to download a certian file from the internet, it can raise a NoInternetConnection exception to inform you when the internet connection is down. This allows you to take a certain action based upon that exception being raised.
Now you may wondering why. In the second case you couldn't simply use a conditional statement to test if there was an internet connection before trying to use it. The reason you'd choose the later versus the former is because of the motto in Python that "asking for forgiveness is easier than asking for permission." This basically means that it's easier to ask Python to catch an exception if one is thrown, than to try to tiptoe around all possible errors using conditional statements.
In the end, its not about "Do you implement your own Exceptions in Python?", but "When do you implement your own Exceptions in Python?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With