Skip to content Skip to sidebar Skip to footer

Implementing Python Exceptions

I'm having some problems implementing an exception system in my program. I found somewhere the following piece of code that I am trying to use for my program: class InvalidProgramS

Solution 1:

Your custom exceptions don't actually need to take parameters at all. If you haven't got any particular error message or state to encapsulate in the Exception, this will work just fine:

classMyException(Exception):
    pass

This would allow your program to catch cases of this exception by type:

try:
    raise MyException()
except MyException:
    print"Doing something with MyException"except:
    print"Some other error occurred... handling it differently"

If you want the Exception to have some meaningful string representation, or have properties that would provide your application greater details on what went wrong, that's when you pass additional arguments to the constructor. The number, name and type of these arguments is not really pre-defined by Python... they can be anything. Just be sure to provide a custom __str__ or __unicode__ method so you can provide a meaningful text depiction:

classMyException(Exception):def__init__(self, msg):
        self.msg = msg

    def__str__(self):
        return"MyException with %s" % self.msg

In the case of the example you're quoting, the expr and msg parameters are specific to the fictional case of the example. A contrived scenario for how these might be used is:

defdo_something(expr):
    if'foo'in expr:
        raise InvalidProgramStateException(expr, "We don't allow foos here")
    return5

user_input = 'foo bar'try:
    do_something(user_input)
except InvalidProgramStateException, e:
    print"%s (using expression %s)" % (e.msg, e.expr)

Since it doesn't appear that your application requires it, just drop the parameters you don't require.

Solution 2:

Check this site: Error tutorials Python

Post a Comment for "Implementing Python Exceptions"