How can I replace an error with a print without terminating the program? Python 3

Asked

Viewed 122 times

0

If I create a variable with an input that only receives integer numbers (int) and put other types of numbers or even letters, it will generate an error and the program will terminate.

I was wondering if you have a way to replace the bug with a custom error message, without shutting down the program.

  • I’m sure it’s duplicate, but I haven’t found the existing question.

1 answer

1


You can treat the error with a Try/except block, something like that:

def entrar_dados():
    try:
        numero = int(input('Entre com um numero: '))
    except ValueError as e:
        print('Voce nao digitou um numero valido', e)

    # Continuação do código

Adding more rules to your program after value capture or error, it will continue running normally.

  • 2

    It is better to specify the exception ValueError in the except to ensure you are capturing the correct exception.

  • @Anderson Carlos Woss thank you for the suggestion. I edited the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.