Handling Errors & Exceptions In: Python
Handling Errors & Exceptions In: Python
Q. What is ‘exception’?
A. Any error which happens during the execution of the code is an exception.
These errors are also called exceptions. Because they usually indicate that
something exceptional (& bad) has happened.
There are several terms and phrases used while working with exceptions. These
are:
Exception: This term could mean of two things. First, the condition that results in
abnormal program flow or it could be used to refer to an object that represents
the data condition. Each exception has an object that holds information about it.
‘Except’ block or ‘catch’ block: Code that handles an abnormal condition is said to
“except” the exception.
‘Throw’ or ‘raise’ block: When an abnormal condition to the program flow has
been detected, an instance of an exception object is created. It is then “thrown” or
“raised” to code that will catch it.
Try block: A set of code that might have an exception thrown in it.
o Right Code
>>>print (“Hello World”)
Hello World
Run-time Error: This error doesn’t appear until after the program has started
running. It is a program error that causes abnormal program termination during
execution. These are like ZeroDivisionError, NameError, TypeError, ValueError,
etc. Example;
o X = (a + b) / c
o The above statement is grammatically correct and will also produce
correct result as soon as c ≠ 0. As soon as c = 0 the code will produce an
error.
o #Python Program
c=0
a = int(input(“Enter value of a: ”))
b = int(input(“Enter value of b: ”))
X = (a + b) / c
Print(“The value of X is: ”, X)
#Python Program Output
Enter the value of a: 20
Enter the value of b: 5
Traceback(most recent call last):
File”C:/Program Files/Python64/Python Program”, line 5, in
<module>
X = (a + b) / c
ZeroDivisionError: division by zero
Value Error: Raised when the correct data type is supplied, but it is not an
appropriate value. For example,
o X = int(input(“Please enter a number: ”))
Please enter a number: re
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
X = int(input(“Please enter a number: ”))
ValueError: invalid literal for int() with base 10: ‘re’
Zero Division Error: When a division expression has zero as the denominator,
this causes Zero Division Error to be raised. For example,
o >>>print(55/0)
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(55/0)
ZeroDivisionError: division by zero
Attribute error: This type of error raises when you are trying to access an
attribute or method that does not exist. If an AttributeError indicates that an object
has NoneType, that means that it is none. For example,
o >>>class Student:
Def_int_(self):
Self.rollno = 100
Self.name = “Ishan”
>>>St = Student()
>>>print(St.Fees)
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(St.Fees)
AttributeError: ‘Student’ object has no attribute ‘Fees’
Index Error: The index you are using to access a list, string, or tuple is greater
than it’s length minus one. When you access the index of a sequence out of it’s
range, then it will raise an exception. For example,
o >>>a = []
>>>print (a[5])
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(a[5])
IndexError: list out of range
EOF Error: This type of error occurs when there is no record or data to read
from a file. For example.
o Eobj = open(“EMD.DAT”, ‘rb’)
try:
while True:
Emp=[]
Emp=load(Eobj)
Print(EMP)
Except EOFError:
Print(‘End of file encounter’)
Key Error: This type of error occurs when we access a key which does not exist
in a dictionary. For example,
o >>>ListMonths = {‘January’:31, ‘February’:28, ‘March’:31, ‘April’:30,
‘May’:31}
>>>print(ListMonths[“April”])
30
>>> print(ListMonths[“August”])
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(ListMonths[“August”])
KeyError: ‘August’
Handling Exceptions
Exception handling is all about ensuring when your program encounters an issue, it will
continue to run and provide informative feedback to the end-user or program
administrative. So, effective exception handling will make your programs more robust
and easier to debug.
Try…except Blocks