Error handling in python.

Today we will look how to handle errors in python.

Handling errors refers the way how python code will deal when our program face any error.

Program

## here we will look how to deal
## with errors or exceptions that
## can occur in a program
def test_int():
    try:
        num1 = int(input("Enter a number : "))
        print(num1)
        # if error occured, goto except block.
    except ValueError as error:
        print("Not a valid number, please enter a valid number")
        print(error)
        test_int()


test_int()

We have added our code inside “try” block and catched the error generated by the code and ran the function test_int again to run this loop till condition is satisfied.

 

Output

/Users/saket/PycharmProjects/1helloworld/venv/bin/python /Users/saket/PycharmProjects/1helloworld/error_handling.py
Enter a number : ff
Not a valid number, please enter a valid number
invalid literal for int() with base 10: 'ff'
Enter a number : rr
Not a valid number, please enter a valid number
invalid literal for int() with base 10: 'rr'
Enter a number : fff
Not a valid number, please enter a valid number
invalid literal for int() with base 10: 'fff'
Enter a number : 4
4

Leave a Reply

Your email address will not be published.