Proper way to handle errors in a module

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 12 20:43:06 EDT 2011


On Thu, 12 May 2011 15:26:27 -0500, Tycho Andersen wrote:

> On Thu, May 12, 2011 at 03:12:39PM -0500, Andrew Berg wrote:
>> On 2011.05.12 02:25 PM, MRAB wrote:
>> > You can raise an exception wherever you like! :-)
>> If I raise an exception that isn't a built-in exception, I get
>> something like "NameError: name 'HelloError' is not defined". I don't
>> know how to define the exception.
> 
> You'll have to define it, as you would anything else (exceptions are
> just regular "things"; in fact you can raise anything that's a class or
> instance).

Not quite.

>>> raise 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be classes or instances, not int

Not a very good error message, because 42 is an instance!

>>> isinstance(42, int)
True

In Python 3, you get a better error message, and further restrictions on 
what you can raise:

>>> raise 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException


In general, you should always subclass Exception rather than 
BaseException. There are, er, exceptions, but for error-handling you 
normally should inherit from Exception directly, or some sub-class like 
ValueError, KeyError, etc.




-- 
Steven



More information about the Python-list mailing list