Exception Handling_Theory

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Computer Science/Python


CHAPTER-3 : EXCEPTION HANDLING IN PYTHON
Introduction :
Sometimes while executing a Python program, the program does not execute at all or the program
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, exceptions are errors that get triggered
automatically. However, exceptions can be forcefully triggered and handled through program code. In
this chapter, we will learn about exception handling in Python programs.
Different types of exceptions in python:
In Python, there are several built-in exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:
 Syntax Error: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
 Type Error: This exception is raised when an operation or function is applied to an object of the

®
wrong type, such as adding a string to an integer.
 Name Error: This exception is raised when a variable or function name is not found in the current
scope.
 Index Error: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
 Key Error: This exception is raised when a key is not found in a dictionary.
 Value Error: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not represent
a valid integer.
 Attribute Error: This exception is raised when an attribute or method is not found on an object,
such as trying to access a non-existent attribute of a class instance.
 IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due
to an input/output error.
 Zero Division Error: This exception is raised when, an attempt is made to divide a number by zero.
 Import Error: This exception is raised when, an import statement fails to find or load a module.
 EOFError: This exception is raised when, one of the file method i.e. read(), readline() or
readlines(), try to readbeyound the file.
 IndentationError: This exception is raised for incorrect indentation.
Example: print "Good Morning"
Syntax Error: Missing parentheses in call to 'print'. Did you mean print (...)?
Example: a=10
b="Hello"
c= a+b
Type Error: unsupported operand type(s) for +: 'int' and 'str'
Example: marks =450
A= marks/0
print (A)
ZeroDivisionError: division by zero
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an
error. This error does not stop the execution of the program. However, it changes the normal flow of
the program.

44 E
CBSE

RAISING EXCEPTIONS
Python interpreter raises (throws) an exception when an error is detected. Python 5 handlers are
designed to execute when a specific exception is raised. Programmers can also forcefully raise
exception in a program using the raise and assert statements.
Once an exception is raised, no further statement in the current block of code is executed. So, raising
an exception involves interrupting the normal flow exception of program and jumping to that part of
the program (exception handler code) which is written to handle such exceptional situations.
THE RAISE STATEMENT
If a condition does not meet our criteria but is correct according to the Python interpreter, we can
intentionally raise an exception using the raise keyword. We can use a customized exception in
conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we may do so as

®
follows:
Example: num = [2, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is
{len(n um)}" )
Exception (Index Error): Lenght of the given list must be less than or equal to 3 but is 4
Example: try:
raise NameError("Hi There")
except NameError:
print("An Exception")
raise
An Exception
NameError: Hi There
THE ASSERT STATEMENT
An assert statement in Python is used to test an expression in the program code. If the result after
testing comes false, then exception is raised. This statement is generally used in the beginning of the
function or after a function call to check for valid input.
The Syntax for assert statement is:
assert Expressions[, Argum
ent]
Example: #Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)
#Calling function and passing the values
print( square_root( 36 ) )
print( square_root( -36 ) )

E 45
Computer Science/Python

TheAssertException, line 4, in square_root
assert ( Number < 0), "Give a positive"
AssertionError: Give a positive
Python Exception Handling Mechanism
Exception handling is managed by the following 3 keywords:
1. try
2. except
3. finally
Try Statement
A try statement includes keyword try, followed by a colon (:) and a suite of code in which exceptions
may occur. It has one or more clauses.
During the execution of the try statement, if no exceptions occurred then, the interpreter ignores the
exception handlers for that specific try statement.

®
In case, if any exception occurs in a try suite, the try suite expires and program control transfers to the
matching except handler following the try suite.
Syntax:
try:
statement(s)
Except Statement
An except statement includes keyword except, followed by a colon (:) and catches the exception inside
the exception block are to be executed.
try:
# code that may cause exception
except:
# code to run when exception occurs

Try with Else Clause


Python also supports the else clause, which should come after every except clause, in the try, and
except blocks. Only when the try clause fails to throw an exception the Python interpreter goes
on to the else block.
Here is an instance of a try clause with an else clause.
Example : # Python program to show how to use else clause with try and except clauses
# Defining a function which returns reciprocal of a number
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
# Calling the function and passing values
reciprocal( 4 )
reciprocal( 0 )
46 E
CBSE

Output: 0.25
We cannot divide by zero
Description: In above example try block generate an exception inside this block when num1=0 put in
function by reciprocal(0) then except block it caught and print suitable statement "We cannot divide by
zero".
Analysis:
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by an except block.When an exception occurs, it is caught by
the except block. The except block cannot be used without the try block.
Finally Statement in Python
Finally block always executes irrespective of an exception being thrown or not. The final
keyword allows you to create a block of code that follows a try-catch block.

®
Finally, clause is optional. It is intended to define clean-up actions which should be that executed
in all conditions.
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output
Welcome, world!
KeyboardInterrupt

Example: # Python code to show the use of finally clause


# Raising an exception in try block
try:
div = 4 // 0
print(div)
# this block will handle the exception raised
except ZeroDivisionError:
print("Atepting to divide by zero")
# This will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )
Output: Atepting to divide by zero
This is code of finally clause
Let's apply exception handling in data file.
try:
filename= 'D:\ \testfile.txt'
with open(filename) as f_obj:
contents = f_obj.read()
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
This will produce the following result, if you are not allowed to write in the file :

E 47
Computer Science/Python

Error: can't find file or read data
Another example of error handling in data file:
import pickle
try:
with open('data.pkl', 'rb') as f:
data = pickle.load(f)
except FileNotFoundError:
print("File not found.")
except pickle.UnpicklingError:
print("Error unpickling file.")
else:
print("File read successfully.")
finally:

®
f.close()
If the file is not found or there is an error while unpickling the file, we catch the exception and print an
error message.
Error: File not found.

48 E

You might also like