There is a list standard python exceptions that we should watch out, but I don't think these are the ones we should raise ourselves, cause they are rarely applicable.
I'm curious if there exists a list within standard python library, with exceptions similar to .NET's ApplicationException, ArgumentNullException, ArgumentOutOfRangeException, InvalidOperationException — exceptions that we can raise ourselves?
Or is there different, more pythonic way to handle common error cases, than raising standard exceptions?
EDIT: I'm not asking on how to handle exceptions but what types I can and should raise where needed.
Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
If the error matches the description of one of the standard python exception classes, then by all means throw it.
Common ones to use are TypeError
and ValueError
, the list you linked to already is the standard list.
If you want to have application specific ones, then subclassing Exception or one of it's descendants is the way to go.
To reference the examples you gave from .NET
ApplicationException
is closest to RuntimeError
ArgumentNullException
will probably be an AttributeError
(try and call the method you want, let python raise the exception a la duck typing)
AttributeOutOfRange
is just a more specific ValueError
InvalidOperationException
could be any number of roughly equivalent exceptions form the python standard lib.
Basically, pick one that reflects whatever error it is you're raising based on the descriptions from the http://docs.python.org/library/exceptions.html page.
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