In previous example, you learned how to catch the exceptions. But you don't know the type of error that occurred. Every exception has a certain type. The types in the example are ZeroDivisionError, NameError, and TypeError. Type is written in the error message. Consider a different program divide1.py:
def divide1():
num = int(raw_input("Enter the number "))
c = 45/num
print c
divide1()
In the given program, when we give the input from the keyboard, the input string will be converted into int type.
Let's run program with different inputs:
When we give the input 5, then the program returns 9. When we supply a string instead of a number, then the interpreter returns a message with a ValueError error as highlighted under red line. When number 0 is supplied, then ZeroDivisionError is returned. By using multiple exception blocks, you can handle both the exceptions.
Refer to the program divide1.py:
def divide1():
try:
num = int(raw_input("Enter the number "))
c = 45/num
print c
except ValueError :
print "Value is not int type"
except ZeroDivisionError :
print "Don't use zero"
else:
print "result is ",c
divide1()
In the preceding program, multiple exceptions have been handled and a crafted message has been displayed. Let's see the output:
In the preceding output, customized messages have been displayed so that the user can understand his mistake.