Pass variable to an exception?
<p>I am trying to learn Python and I want to know if it is possible to pass a variable to an <code>Exception</code>? This is the code I have:</p>

<pre><code>try:
    staffId = int(row['staffId'])
    openingSalary = int(row['initialSalary'])
    monthsWorked = float(row['monthsWorked'])
except CutomException:
    pass

class CustomException(ValueError): # raised if data conversion fails
    def __init__(self):
        print("There was a problem converting data")
</code></pre>

<p>I want to pass <code>staffId</code> to the exception so that I can print something like: </p>

<p>print("There was a problem converting data for staff Id: ", staffId)</p>

<p>I tried this with no success: <a href="http://stackoverflow.com/questions/6626816/how-to-pass-a-variable-to-an-exception-when-raised-and-retrieve-it-when-excepted">How to pass a variable to an exception when raised and retrieve it when excepted?</a></p>

<p>The custom exception will need to be <code>raise</code>'d conditionally by the <code>try</code> block to include the <code>staffId</code> variable. As an example, when the <code>staffId</code> is a <code>str</code> and not an <code>int</code>.</p>

<pre><code>try:
    # conditionalize a scenario where you'd want to raise an error
    #  (e.g. the variable is a string)
    if type(staffId) is str:
        raise CustomException(staffId)
    else:
        staffId = int(row['staffId'])
        openingSalary = int(row['initialSalary'])
        monthsWorked = float(row['monthsWorked'])
except CutomException:
    pass

class CustomException(ValueError): # raised if data conversion fails
    def __init__(self, id):
        print("There was a problem converting data %s" % id)
</code></pre>

python exception