Using "Try and Exception" for validating data

(https://gist.github.com/52bacb772d59802e3c689ad3ff13f9d1)

I always have a problem with try and exception. I don’t know how to adapt it properly, even though I try to search examples of using.

For this exercise:
When creating a patient’s data, I like to validate if the sex and smoker are integer and the values should be 0 or 1 only.

sex : 0 for Female, 1 for Male
smoker : 0 for non-smoker, and 1 for smoker.

if not correct, the init should not pass all the parameter and raise exception

class Error(Exception):
  pass
class ZerooronevalueError(Error):
  pass
class NumericalvalueError(Error):
  pass
class Patient:
  def __init__(self, name, age, sex, bmi, num_of_children, smoker):
    self.name = name
    self.age = age
    self.sex = sex
    self.bmi = bmi
    self.num_of_children = num_of_children
    self.smoker = smoker
    try:
      if not isinstance(self.sex, int):
        raise NumericalvalueError
      if self.sex != 0 or self.sex != 1:
        raise ZerooronevalueError
    except NumericalvalueError:
      print("Sex should be numerical value.")
    except ZerooronevalueError:
      print("Sex can be only '0' for Female or '1' for Male.")

and I wrote another method

  def patient_profile(self):
    patient_information = {}
    patient_information['Name'] = self.name
    patient_information['Age'] = self.age
    patient_information['Sex'] = self.sex
    patient_information['BMI'] = self.bmi
    patient_information['Number of Children'] = self.num_of_children
    patient_information['Smoker'] = self.smoker
    return patient_information

When I run the code as follows;

patient2 = Patient("Doraemon", 25, 'male', 22.2, 0, 0)
print(patient2.patient_profile())

It raised exception, but still pass on the parameter. Thus, when I called patient_profile() method, I still got the information that ‘Sex’ : 'Male.

Sex should be numerical value.
{'Name': 'Doraemon', 'Age': 25, 'Sex': 'Male', 'BMI': 22.2, 'Number of Children': 0, 'Smoker': 0}

I tried to swap try, exception before assigning the parameter (self.age =age , etc.) and use else: after exception but the terminal showed that there was not age value.

Thank you everybody in advance for your suggestions.

You’ve still assigned part of your instance because of the order of execution. As for why your code runs it’s because you’ve set up ways to catch the exceptions. Therefore it’s perfectly happy to continue, you’ve handled the exception. If you wanted it to raise an error and cancel further execution of the program then re-raise the exceptions you caught, e.g.

except NumericalvalueError:
    print("Sex should be numerical value.")
    raise

Have a little nosey through the docs for a little more info about using raise-

1 Like