CSE Notes Plus Two
CSE Notes Plus Two
Reprint 2025-26
handled in the except block. While writing or debugging
a program, a user might doubt an exception to occur
in a particular part of the code. Such suspicious
lines of codes are put inside a try block. Every try
block is followed by an except block. The appropriate
code to handle each of the possible exceptions (in
the code inside the try block) are written inside the
except clause.
While executing the program, if an exception is
encountered, further execution of the code inside the
try block is stopped and the control is transferred to
the except block. The syntax of try … except clause
is as follows:
try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is
encountered]
Consider the Program 1-2 given below:
Program 1-2 Using try..except block
Reprint 2025-26
rerun the program. When a syntax error is encountered
while working in shell mode, Python displays the name
of the error and a small description about the error as
shown in Figure 1.1.
Reprint 2025-26
Program 1-6 Use of finally clause
Reprint 2025-26
1.3 Exceptions
Even if a statement or expression is syntactically
correct, there might arise an error during its execution.
For example, trying to open a file that does not exist,
division by zero and so on. Such types of errors might
disrupt the normal execution of the program and are
called exceptions.
An exception is a Python object that represents an
error. When an error occurs during the execution of a
program, an exception is said to have been raised. Such
an exception needs to be handled by the programmer
so that the program does not terminate abnormally.
Therefore, while designing a program, a programmer
may anticipate such erroneous situations that may arise
during its execution and can address them by including
appropriate code to handle that exception.
It is to be noted that SyntaxError shown at Figures
1.1 and 1.3 is also an exception. But, all other exceptions
are generated when a program is syntactically correct.
Reprint 2025-26
4 KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key
while executing a program due to which the normal flow of the
program is interrupted.
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().
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.
Reprint 2025-26
handlers are designed to execute when a specific
exception is raised. Programmers can also forcefully
raise exceptions 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 execution of program and jumping to that part of
the program (exception handler code) which is written
to handle such exceptional situations.
1.5.1 The raise Statement
The raise statement can be used to throw an exception.
The syntax of raise statement is:
raise exception-name[(optional argument)]
The argument is generally a string that is displayed
when the exception is raised. For example, when an
exception is raised as shown in Figure 1.5, the message
“OOPS : An Exception has occurred” is displayed along
with a brief description of the error.
Reprint 2025-26
As we can see in Figure 1.6, in addition to the
error message displayed, Python also displays a stack
Traceback. This is a structured block of text that
contains information about the sequence of function
calls that have been made in the branch of execution of
code in which the exception was raised. In Figure 1.6,
the error has been encountered in the most recently
called function that has been executed.
Reprint 2025-26
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))
Reprint 2025-26
of the important points regarding exceptions and their
handling:
• Python categorises exceptions into distinct types so
that specific exception handlers (code to handle that
particular exception) can be created for each type.
• Exception handlers separate the main logic of the
program from the error detection and correction
code. The segment of code where there is any
possibility of error or exception, is placed inside one
block. The code to be executed in case the exception
has occurred, is placed inside another block. These
statements for detection and reporting the exception
do not affect the main logic of the program.
• The compiler or interpreter keeps track of the exact
position where the error has occurred.
• Exception handling can be done for both user-defined
and built-in exceptions.
Reprint 2025-26
executing a suitable handler is known as catching the
exception. If the runtime system is not able to find an
appropriate exception after searching all the methods in
the call stack, then the program execution stops.
The flowchart in Figure 1.8 describes the exception
handling process.
Reprint 2025-26
In the code, two types of exceptions (ZeroDivisionError
and ValueError) are handled using two except blocks
for a single try block. 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 of the try..except
block. The Program 1-4 given below along with the
output given in Figure 1.11 explains this.
Program 1-4 Use of except without specifying an exception
Reprint 2025-26
only if some exception is raised in the try block. But if
there is no error then none of the except blocks will
be executed. In this case, the statements inside the
else clause will be executed. Program 1-5 along with
its output explains the use of else block with the try...
except block.
Program 1-5 Use of else clause
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
Output:
Reprint 2025-26
While executing the above code, if we enter a
non-numeric data as input, the finally block will be
executed. So, the message “OVER AND OUT” will be
displayed. Thereafter the exception for which handler is
not present will be re-raised. The output of Program 1-7
is shown in Figure 1.13.
Summary
• Syntax errors or parsing errors are detected when
we have not followed the rules of the particular
programming language while writing a program.
Reprint 2025-26
h apter
C
Exception Handling
1 in Python
In this Chapter
»» Introduction
»» Syntax Errors
»» Exceptions 1.1 Introduction
»» Built-in Exceptions Sometimes while executing a Python program, the
»» Raising Exceptions program does not execute at all or the program
executes but generates unexpected output or
»» Handling Exceptions
behaves abnormally. These occur when there are
»» Finally Clause 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.
Reprint 2025-26
Notes • When syntax error is encountered, Python displays
the name of the error and a small description
about the error.
• The execution of the program will start only after
the syntax error is rectified.
• An exception is a Python object that represents
an error.
• Syntax errors are also handled as exceptions.
• The exception needs to be handled by the
programmer so that the program does not
terminate abruptly.
• When an exception occurs during execution
of a program and there is a built-in exception
defined for that, the error message written in that
exception is displayed. The programmer then has
to take appropriate action and handle it.
• Some of the commonly occurring built-in
exceptions are SyntaxError, ValueError,
IOError, KeyboardInterrupt, ImportError,
EOFError, ZeroDivisionError, IndexError,
NameError, IndentationError, TypeError,and
OverFlowerror.
• When an error is encountered in a program,
Python interpreter raises or throws an exception.
• Exception Handlers are the codes that are
designed to execute when a specific exception
is raised.
• Raising an exception involves interrupting the
normal flow of the program execution and jumping
to the exception handler.
• Raise and assert statements are used to raise
exceptions.
• The process of exception handling involves
writing additional code to give proper messages
or instructions to the user. This prevents the
program from crashing abruptly. The additional
code is known as an exception handler.
• An exception is said to be caught when a code
that is designed to handle a particular exception
is executed.
• An exception is caught in the try block and
handles in except block.
Reprint 2025-26
• The statements inside the finally block are always
executed regardless of whether an exception
occurred in the try block or not.
Exercise
1. “Every syntax error is an exception but every exception
cannot be a syntax error.” Justify the statement.
2. When are the following built-in exceptions raised? Give
examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError
3. What is the use of a raise statement? Write a code to
accept two numbers and display the quotient. Appropriate
exception should be raised if the user enters the second
number (denominator) as zero (0).
4. Use assert statement in Question No. 3 to test the
division expression in the program.
5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception
6. Explain catching exceptions using try and except block.
7. Consider the code given below and fill in the blanks.
print (" Learning Exceptions...")
try:
num1= int(input ("Enter the first number"))
num2=int(input("Enter the second number"))
quotient=(num1/num2)
print ("Both the numbers entered were correct")
except _____________: # to enter only integers
print (" Please enter only numbers")
except ____________: # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
___________: # to be executed at the end
print(" JOB OVER... GO GET SOME REST")
Reprint 2025-26
Notes 8. You have learnt how to use math module in Class
XI. Write a code where you use the wrong number of
arguments for a method (say sqrt() or pow()). Use the
exception handling process to catch the ValueError
exception.
9. What is the use of finally clause? Use finally clause in
the problem given in Question No. 7.
Reprint 2025-26