Home > Software design >  how do i raise exception when i promp user to enter a number
how do i raise exception when i promp user to enter a number

Time:12-08

i want to get input from user to fill the empty list. if user enters a negative integer- it will not get appended rather a ValueError will be raised.

nameList = []
count = 0 
try:
    while count < 5:
        num = int(input('Enter a number: '))
        if num < 0:
            except NameError:
                print('Positive integers only!')
        numList.append(num)
        count = count   1
        

print(numList)

I tried adding assertion after the try and before the while but I got syntax error since num is not defined.

CodePudding user response:

Use raise to raise an exception:

        num = int(input('Enter a number: '))
        if num < 0:
            raise ValueError('Positive integers only!')

Use except to handle an exception raised in the corresponding try (that is, the except and try need to be at the same indentation level). If you wanted to handle the ValueError by printing an error message and continuing the loop, you might do:

    try:
        num = int(input('Enter a number: '))
        if num < 0:
            raise ValueError('Positive integers only!')
    except ValueError as e:
        # This will happen if the user entered something
        # non-numeric OR a valid but negative number.
        print(e)
        continue

CodePudding user response:

There's little point to raising an exception that you intend to immediately catch. Just use continue to go back to the top of the loop body.

nameList = []
count = 0 
while count < 5:
    try:
        num = int(input('Enter a number: '))
    except ValueError:
        print("Not an integer")
        continue
    if num < 0:
        print('Positive integers only!')
        continue

    numList.append(num)
    count = count   1

While you are at it, use a for loop to repeat the body (successfully) 5 times, without the need to explicitly increment count:

for _ in range(5):  # _ instead of count to emphasize that you don't use the variable
    try:
        num = int(input('Enter a number: '))
    except ValueError:
        print("Not an integer")
        continue
    if num < 0:
        print('Positive integers only!')
        continue

    numList.append(num)

I should soften this a little. If you intend to handle an exception raised by int and your own explicit exception in exactly the same way, I wouldn't say "no" to using raise ValueError("Not an integer") in the try block. But, this is an opportunity to provide a different error message for non-integers and negative integers, so I would still recommend separating the two checks as above.

  • Related