In our last exercise we scripted a software to order pizza. That was a huge code until now. Sometime while making big code like that we can make some mistake. Some time a user can enter wrong values which can cause error. e.g we asked for numerical values for math algorithm and user enters a alphabet. Or this could be any issue. To solve error like these we use Python error handling functions “try:except”. They work more like “if-else” but instead of condition in “if” function,“try” function check if code is executed without error.
Let’s see and example to understand this better.
a = input("Enter first number\n>") b = input("Enter second number\n>") try: print(int(a) + int(b)) except: print("One or more values are not numeric")
In first 2 line we are taking input from users. Note “\n” in input function this is used to create an “>” prompt for user in next line.
Run the code
Now run the code and try passing different values.
Its important to handle error and pass some message. And “YES” you can use nested try:except as if:else.