Chapter 1 - Exception Handling in Python
Chapter 1 - Exception Handling in Python
Introduction:
Sometimes while executing a program the program does not execute at all
or it executes but generates unexpected output or behaves abnormally.
These occur when there are syntax errors, runtime errors or logical errors in the
code.
In Python exception are errors that get triggered automatically .
Syntax error:
The errors which occur when the user has not followed the rules of particular
programming language while writing a program.
These errors are also called as parsing errors.
When a syntax error is encountered while working in shell mode, Python displays
the name of the error and small description about the error and a suggestion to
rectify it as shown below.
1
Chapter 1: Exception handling
3. IOError: It is raised when the file specified in a program statement
cannot be opened. (Requested file cannot be found)
4. KeyboardInterrupt: It is raised when the user accidentally hits
the Delete or Esc key while executing a program.
5. ImportError: It is raised when the requested module definition is
not found.
6. EOFError: It is raised when the end of file condition is reached
without reading any data by input() function.
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.
Here, argument is generally string that is to be displayed when the exception is raised.
Example 1:
>>>raise Exception( “OOPS!! An exception has occurred”)
OUTPUT:
Exception: OOPS!! An exception has occurred
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))
OUTPUT:
Use of assert statement
10000
None
AssertionError : OOPS.... Negative Number
In the above example if negative value is entered, then assertion error will be thrown
and displays the message “OOPS.... Negative Number”
Need for exception handling: Exception handling is a useful technique, that captures
runtime error and handles them to avoid the program from getting crashed.
3
Chapter 1: Exception handling
Process of handling exceptions:
When an error occurs Python interpreter creates an object called exception object.
The object is handed over to the runtime system. This process of creating an
exception object and handing it over to the run time system is called throwing an
exception.
The runtime system searches the entire program for exception handler.
This hierarchical search in riverse order continue till the exception handler is found
This entire list of methods or functions is known as call stack.
When is suitable handler is found in the call stack it is executed by the runtime
process.
This process of executing a suitable handler is known as catching the exception.
Try .. except block: Exceptions if any are caught in the try block and handled in the
except block
try block contains those lines of code that may give rise to an exception.
Except block contains exception handling code.
Every try block is followed by except block.
When exception occurs inside try block the remaining statements in the try block are
skipped and control is transferred to except block.
4
Chapter 1: Exception handling
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)
5
Chapter 1: Exception handling
Finally clause:
The try statement can also have an optional finally clause.
The statements inside finally block are always executed regardless of whether an
exception has occurred in the try block or not.
finally clause is used for while working with files to ensure that the file object is
closed.
Finally clause should always be placed at the end of try clause, after all except blocks
and the else block.
ASSIGNMENT QUESTIONS:
1. What is an exception in Python?
2. Explain any five built in exceptions in Python.
3. What is meant by throwing(raising) an exception?
4. What is the use of raise and assert statements in python? Give the syntax
and example for each.
5. What is exception handling ?
6. What do you mean by catching exception?
7. What is the use of try.. except block? Give the syntax and an example.
8. What is the use of multiple except blocks in try..except block?
9. Explain the use of try…except…else clause with an example.
10. What is the use of finally clause? Where is it placed in the program, if used?
6
Chapter 1: Exception handling