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:
class MyException(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:
class MyException(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:
def do_something(expr):
if 'foo' in expr:
raise InvalidProgramStateException(expr, "We don't allow foos here")
return 5
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.