Chapter 1 Exception Handling
Chapter 1 Exception Handling
EXCEPTION HANDLING
1.1 Introduction
In Python, exceptions are errors that get triggered automatically.
However, exceptions can be forcefully triggered and handled through
program code.
1.3 Exceptions
It is an error that occurs during the execution of the program,
which disrupts the normal flow of the program.
Ex: Trying to open a file that does not exist, division by zero and so on.
1
7 ZeroDivisionError It is raised when the denominator in a division
operation is zero.
8 IndexError It is raised when the index or subscript in a
sequence is out of range.
9 NameError It is raised when a local or global variable name is
not defined.
10 IndentationError It is raised due to incorrect indentation in the
program code.
11 TypeError It is raised when an operator is supplied with a
value of incorrect data type.
12 OverFlowError It is raised when the result of a calculation
exceeds the maximum limit for numeric data type.
2
Syntax:
assert Expression[,arguments]
On encountering an assert statement, Python evaluates the
expression. If this expression is false, an AssertionError exception is
raised which can be handled like any other exception.
Ex: assert(number>=0),"OOPS...Negative Number"
For handling multiple errors, we can have multiple except blocks for a
single try block.
Ex:
try:
numerator=50
denom=int(input("Enter the denominator:"))
print (numerator/denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
except:
5
print("OOPS.....SOME EXCEPTION RAISED")
When an exception is raised, a search for the matching except block is
made till it is handled. If no match is found, then the program terminates.
However, if an exception is raised for which no handler is created by the
programmer, then such an exception can be handled by adding an except
clause without specifying any exception. This except clause should be added
as the last clause.