[Tutor] custom error classes: how many of them does one need?

Alan Gauld alan.gauld at btinternet.com
Fri Jul 5 00:55:32 CEST 2013


On 04/07/13 20:40, Albert-Jan Roskam wrote:

> creating a module that can raise several distinct errors, a common practice is
> to create a base class for exceptions defined by that module, and subclass that
> to create specific exception classes for different error conditions"

Yes, although not usually too many...

> Given that I have many retcodes,

return codes (aka retcodes?) are semantically different from
exception or error codes. You should clearly distinguish between
valid return codes and error codes.

Or do you mean by retcode that you have multiple sub-error codes?
That's usually a messy solution... It puts extra work onto the
user of your code in disentangling the mess.

> is it a better approach to define a class factory that generates
 > a custom exception for each retcode on-the-fly?

That shouldn't really be necessary unless you've gone down the messy 
multiple levels of error approach. Usually its easier to just define new 
Error classes. They don;t need to contain much!

> retcodes = {0: "OK", 1: "Error_X", 2: "Error_Y"}

You don't need the first one. If its OK its OK there should be no 
exception. The other two should be separate error types I suspect.

> #############################
> # [A] one custom exception for all purposes, but with a descriptive message
> #############################
>
> class single_custom_exception(Exception):
>      def __init__(self, retcode, message):
>          self.retcode = retcode
>          message += " [%s]" % retcodes.get(retcode)
>          Exception.__init__(self, message)

Why not

class Error_X(Exception):pass
class Error_Y(Exception):pass

Just a thought... Or is there some fancy extra functionality required
that you're not telling us about?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list