Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where's the standard python exception list for programmes to raise?

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.

like image 634
Janusz Skonieczny Avatar asked Nov 04 '10 11:11

Janusz Skonieczny


People also ask

How do I get a list of exceptions in Python?

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!”)

How do you raise exceptions in Python?

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.


1 Answers

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.

like image 156
Glenjamin Avatar answered Sep 22 '22 13:09

Glenjamin