Saturday, January 11, 2020

Exception Handling

Welcome Friends!

Today we are going to discuss Exception Handling. Well, sometimes our python or user don't respond to the code it is designed and result in errors or exceptions. Let's take an example to understand it better. Suppose our program expects 2 numbers and it performs addition on these numbers and gives the result. Now, if a user enters a number and a string, python will not be able to convert string to a number and will throw an error. To capture these and display a meaningful message on screen we use try and except in python.
num_1 = int(input("Enter 1st number: "))
num_2 = int(input("Enter 2nd number: "))
total = num_1 + num_2
print("Sum of two numbers are {}".format(total))

Now, if we run this we will get an error if we provide a string as an input.
Enter 1st number: 78
Enter 2nd number: u89
Traceback (most recent call last): 
    File "D:/Python_Data/new2python.py", line 3, in <module>
      num_2 = int(input("Enter 2nd number: "))
    ValueError: invalid literal for int() with base 10: 'u89'

No one would like to see this kind of messages. Let's display some meaningful message by capturing this kind of scenario.
try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 + num_2 
    print("Sum of two numbers are {}".format(total))
except: 
    print('Invalid number entered. Please try again')

And if we run this and make a mistake, we will see a message that the user has entered an invalid number and can retry.
Enter 1st number: 44
Enter 2nd number: r55
Invalid number entered. Please try again

Well, this can be put inside a while loop so that it will keep repeating until the user provides a valid input.

Let's take another scenario, our program will ask the user to provide two numbers and the program will divide these numbers and displays results. What if the user enters 0 (zero), in this case, we need to display a different error message. Let's try to fix it.
try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 / num_2 
    print("Division of two numbers are {}".format(total))
except ValueError: 
    print('Invalid number entered. Please try again')
except ZeroDivisionError: 
    print('Cannot divide by zero. Please try again')
except: 
    print('Something really went wrong')

If we run the above code, we will be able to capture the specific error message.
Enter 1st number: 43
Enter 2nd number: 0
Cannot divide by zero. Please try again

By now you must be wondering, how can we know the exception values we need to use? It's simple, just run your code without try and except and once you get the error message, it will let you know the type of message you can use to capture these kinds of scenarios.

When the code goes in production, there can be unknown errors and in that case, we don't want to see a generic error message rather we would also like to capture the exception. To capture the exception and display, let's try this one out.
try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 / num_2 
    print("Division of two numbers are {}".format(total))
except ValueError: 
    print('Invalid number entered. Please try again')
except Exception as e: 
    print('Something really went wrong.\nError message: {}'.format(e))

Now we know how to handle and capture the exceptions, there is one last piece remaining in this section. The final block is known as finally. so it goes like, 
   try: 
      ... 
   except: 
      ... 
   finally: 
      ... 

Like the name suggests, it will be executed irrespective if there is an error or not. In our above example, after the user has provided the numbers and after displaying, we would like to display a thank you note for taking their time to test. Let me show you how we can write it up.


try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 / num_2 
    print("Division of two numbers are {}".format(total))
except ValueError: 
    print('Invalid number entered.')
except ZeroDivisionError: 
    print('Cannot divide by zero.')
except Exception as e: 
    print('Something really went wrong.\nError message: {}'.format(e))
finally: 
    print('Thank you for your time. Have a good day!')

I hope you have enjoyed this. In our next post, we will discuss how to open and write to a file. Stay tuned. 

No comments:

Post a Comment