2

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

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")

I want to pass staffId to the exception so that I can print something like:

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

I tried this with no success: How to pass a variable to an exception when raised and retrieve it when excepted?

Community
  • 1
  • 1
komodo
  • 39
  • 1
  • 7
  • The answer to the question you linked will do what you're looking for (e.g., call `raise CustomException` inside of your `try` block) – Anthony Forloney Oct 07 '16 at 02:22
  • Wouldn't it raise CustomException even of there are no errors in the try block? – komodo Oct 07 '16 at 02:32
  • I provided an answer below to illustrate it further. In short, you need to conditionalize `raise` the `CustomException` to avoid raising the exception every time. – Anthony Forloney Oct 07 '16 at 02:40

3 Answers3

3

The caller of the exception, e.g. the one that raise exception will have to pass an argument to the constructor.

class CustomException(ValueError): # raised if data conversion fails
    def __init__(self, message):
        self.message = message;
        print("There was a problem converting data")


try:
    try:
        staffId = int(row['staffId'])
        openingSalary = int(row['initialSalary'])
        monthsWorked = float(row['monthsWorked'])
    except ValueError as e:
        raise CustomException(e);
except CustomException:
    pass
Ryan
  • 14,392
  • 8
  • 62
  • 102
  • How do I do that in a try...except statement? In my example if the information provided is incorrect, let's say that you pass a string to staffId then the exception gets raised automatically. At least that is how I understand it. – komodo Oct 07 '16 at 02:17
  • 1
    @komodo you can do it with nested exceptions, just pass – Ryan Oct 07 '16 at 02:44
  • Curious, is `Cutom` intended to differ from `Custom`? – NelsonGon Jan 15 '20 at 06:33
1

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

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)
Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
  • The problem is that all the info in row are strings because they come from a csv file that was extracted to a dictionary. Therefore, I can't check if staffId is a string because I already know it is. Good idea though;) – komodo Oct 07 '16 at 10:55
  • @komodo I was using that as a condition from your comment to the other answer. In any event, I think the other answer has what you need. – Anthony Forloney Oct 07 '16 at 11:36
0

I think you should handle the exception in the except block and not inside the exception class.

try:
    raise CustomException(foo)
except CutomException as e:
    print(e.args)
    handle_exception()

class CustomException(Exception):
    def __init__(self, foo):
        super().__init__(foo, bar)
Foreever
  • 7,099
  • 8
  • 53
  • 55