[Tutor] Understanding Custom Exception

Steven D'Aprano steve at pearwood.info
Tue Aug 31 15:25:47 CEST 2010


On Tue, 31 Aug 2010 09:40:54 pm Alex wrote:

> 1. Does it make sense to create a couple of custom exceptions like:
>
>    class CrontabDoesNotExist(Exception): pass
>    class CrontabSyntaxError(Exception): pass
>
>   Or I should use builtin exception?

Yes, it makes sense, although I'd consider making them subclasses of 
more specific exceptions, e.g. perhaps CronTabMissing (shorter name 
than CronTabDoesNotExist) might be a subclass of the error you get when 
you try to open a missing file (IOError if memory serves me right), and 
CronTabSyntaxError might be a subclass of SyntaxError.

Or perhaps not -- you might choose to have a general CronTabError 
exception class, that inherits from Exception, and then inherit from 
that, so that all errors related to CronTab fall under a single 
exception hierarchy. Both strategies are valid.


> 2. Does it make sense to catch an exception raised by a function just
> to raise your own custom exception? For instance
>
> subprocess.check_call(['crontab','-l'])
>
> will raise a CalledProcessError exception if the crontab of the
> current user does not exist. Does it make sense to catch the
> exception just to raise my own custom exception? For instance:
>
> try:
>     subprocess.check_call(['crontab','-l'])
> except CalledProcessError:
>     raise CrontabDoesNotExist()


It certainly does. I'm sure you'll see that technique used in the 
standard library.

[/me goes and looks]

Yep, here you go, in httplib.py:

        # The status code is a three-digit number
        try:
            status = int(status)
            if status < 100 or status > 999:
                raise BadStatusLine(line)
        except ValueError:
            raise BadStatusLine(line)



> Maybe I could also make the CrontabDoesNotExist exception more useful
> printing a message to inform the user that the crontab does not exist
> for the current user.

The point of specific exception types is to be more specific rather than 
less, so yes. If you want to be less specific, you should stick to 
built-in exceptions.


-- 
Steven D'Aprano


More information about the Tutor mailing list