Is it bad practice to raise errors when input doesn't match the requirements?

19 Views Asked by At

Is the following syntax acceptable, or should the raising of the error be replaced by adding the if-clause in the else statement?

Example of raising the error:

def ask_birth_year():
    while True:
        try:
            year = int(input('What is your birth year?'))
            if year < 1890 or year > 2023:
                raise ValueError
        except ValueError:
            print('Please enter a valid birth year')
        else:
            return year

Alternative:

def ask_birth_year():
    while True:
        try:
            year = int(input('What is your birth year?'))
            if year < 1890 or year > 2023:
                raise ValueError
        except ValueError:
            print('Please enter a valid birth year')
        else:
            if year < 1890 or year > 2023:
                print('Please enter a valid birth year')
            else:
                return year

Furthermore, which is the preferred syntax by convention?

0

There are 0 best solutions below