An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program. Python provides a way to handle the exception so that the code can be executed without any interruption.
Problem:-
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
Output:-
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
Solution:-
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
#other code:
print("Hi I am other part of the program")
Output:-
Enter a:10
Enter b:0
Can't divide with zero
Hi I am other part of the program
Common Exceptions:-
Type Error
Type Error Exception is raised when two different or unrelated types of operands or objects are combined.
Name Error
A NameError is raised when you try to use a variable or a function name that is not valid.
Index Error
An IndexError is raised when a sequence reference is out of range.
Exercises:-
Comments
Post a Comment