Exception Handling_Theory
Exception Handling_Theory
Exception Handling_Theory
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
®
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
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