II PUC COMPUTER SCIENCE SCANNER
Chapter-1
EXCEPTION HANDLING IN PYTHON
EXCEPTIONS : - An exception is a Python object that represents an error.
Unexpected error occurs during program execution is known as Exception.
The way of handling anomalous situations in a program-run, is known as Exception Handling.
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.
For Example: print "Good Morning"
Syntax Error: Missing parameters in call to 'print'. Did you mean print (" Good Morning" )?
It is to be noted that Syntax Error in the given example is also an exception.
But all other exceptions are generated when a program is syntactically correct.
Built – in Exceptions:-
Commonly occurring exceptions are usually defined in the compiler/interpreter are called Built
-in exceptions.
Built – in Exceptions in Python
l. SyntaxError: - It is raised when there is an error in the syntax of the Python code. it is also
known as parsing error
2. ValueError: - It is raised when a built- in method or operation received an argument that has
the right data type, but mismatched or inappropriate values.
3. IOError: - It is raised when the file specified in a program statement can not be opened.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 1
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
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.
7. Zero Division Error:- 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.
Some examples for Built-in exceptions:
1. x=int(input(“Enter a number”)
If you enter string then we get ValueError
2. for n in range(0,5):
print(5/n)
ZeroDivisionError
3. import Mymodule:
If Mymodule is not defined ImportError
4. x=8
print(X)
NameError
5. l=[2,3,4]
print(l[4])
IndexError
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 2
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
6. import math
a=math.pow(100000,100000)
OverflowError
7. File=open(“abb.txt”,”r”)
FileNotFoundError
IOError
8. a=”A”
b=5
print(a+b)
TypeError
9. a=5
b=4
if a>b:
large=a
IndentationError
10.from math import sqr
print(sqr(25))
ImportError
11.import maths
ModuleNotFoundError
A programmer can also create custom exceptions to suit One's requirements. These are called
user- defined exceptions.
HANDLING EXCEPTIONS:- It is a process that helps in capturing runtime errors and handling
them so as to avoid the program getting crashed.
Need for Exception Handling: -
1. Python categorises exceptions into distinct types so that specific exception handlers can
be created for each type.
2. Exception handlers separate the main logic of the program from the error detection and
correction code.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 3
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
3. The compiler or interpreter keeps track of the exact position where the error has
occurred.
4. Exception handling can be done for both user-defined and built-in exceptions.
Process of Handling Exception –
When an error occurs, Python interpreter creates an object called the Exception objet.
This object contains information about the error like its type, file name and position in the
program where the error has occurred.
The object is handed over to the runtime system so that it can find an appropriate code to
handle this particular exception. This process of creating an exception object and handling it
over to the runtime system is called throwing an exception.
The runtime system searches the entire program for a block of code, called the exception
handler that can handle the raised exception.
If not found, then it searches for methods in call stack. The entire list of methods is known as
call stack.
When a suitable handler is found in the call stack, it is executed by the runtime process.
The process of 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.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 4
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Steps of handling exception:-
An error encountered in a method
Create exception object.
Exception is raised
Runtime system searches for
exception handler in the current
method
Executes the code Searches for methods in call stack
in reverse sequence
( Catching an Exception)
( Forwarding sure exception)
Program terminates
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 5
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Catching Exceptions: -
An exception is said to be caught when a code that is designed to handle a particular exception
is executed. Exceptions, if any, are caught in the try block and handled in the except block.
try :
Run this code
except:
Execute this code when there is an
exception
else:
No exceptions? Run this code
finally:
Always run this code
try-except block : The try-except block is the fundamental construct for handling exceptions in
Python. It allows developers to specify code that might raise an exception and define how to
handle it if an exception occurs.
Syntax:
try:
Write here the Program statements to be execute
except <exceptionName1>:
If there is an exception, then execute this block
except <exceptionName2>:
If there is an exception, then execute this block
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 6
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
else:
If there is no exception, then execute this block
finally:
The statement will always run (This block contains the code that must execute)
The try block or clause is used for enclosing the code wherein exceptions can take place.
The except block is a group of Python statements that are used to handle a raised exception.
This block should be placed after each try: block.
This block traps the exception and handles it.
The else: clause will execute if there is no exception raised.
The finally block is a place that contains any code that must execute, whether the try: block
raised an exception or not.
It is a ‘must -execute’ block.
All exceptions are subclasses of Exception class.
Example1:
try:
a=int(input(“Enter the value of a”))
print(a)
except:
print("This is not an integer")
Example2:
try:
file=open(“abb.txt”,”r”)
print(file.read())
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 7
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
except:
print("File does not exist")
Use of Multiple except clauses
Example3:
try:
a = float(input(“Enter the value of a” ))
print(1 / a)
except ValueError:
print("Please input a number")
except ZeroDivisionError:
print("Please input a non-zero number")
else:
print(“No exception”)
finally:
print (" it will execute no matter”)
RAISING / FORCING EXCEPTIONS:- Each time an error is detected in a program, the Python
interpreter raises (throws) an exception. Exception 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.
The raise Statement:-
The raise statement can be used to throw an exception.
The syntax of raise statement is:
raise exception_name(optional argument)
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 8
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
The raise keyword forces an exception.
Note :- In this case, the user has only raised the exception but has not displayed any error
message explicitly.
Use of the raise statement to throw an exception
>>> raise Exception ("OOPS !! An Exception has occurred”)
Use of raise statement with built- in exception
a=int(input(“Enter the Numerator”))
b=int(input(“Enter the Denomirator”))
if a==0:
raise ZeroDivisionError(“Denominator can not be zero”)
else:
print(“Quotient=”,a/b)
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 the 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 Expression, [arguments]
Example1:
a=int(input(“Enter the Numerator”))
b=int(input(“Enter the Denomirator”))
assert b!=0, “Denominator can not be Zero”
print(a/b)
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 9
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Example2:
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print(negativecheck(100))
print(negativecheck(-350))
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 10
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
MULTIPLE CHIOCE QUESTIONS(MCQ):-
1. The errors encountered when a user violates the syntax of a programming language while
writing a code are termed as ............... .
a. Syntax error. b. Logical error. c. Runtime error. d. Exception
2. An interrupt or forced disruption that occurs when a program is run or executed is termed
as....... .
a. Compile time error. b. Exception c. Runtime error d. Logical error
3. Which of the following keywords are not specific to exception handling?
a. try. b. except. c. else. d. finally
Reason — The 'else' keyword in Python is not specific to exception handling but rather plays a
role in conditional statements and control flow structures. On the other hand, in exception
handling constructs, the main keywords are 'try,' 'except,' and 'finally.
4. Which block is a mandatory block in exception handling process?
a. try. b. except. c. finally. d. else
Reason — The try block is a mandatory component of the exception handling process because
it encapsulates code that might raise exceptions, allowing them to be caught and handled
effectively.
5. Forced exceptions are indicated using which of the following keywords?
1. try. b. except. c. finally. d. raise
6. An anomalous situations encountered by the program is known as __________.
a. Debugging b. Testing. c. Exception. d. None of these
7. Syntax errors are also known as ____________errors.
a. Runtime b. Logical c. Exception. d. Parsing
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 11
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
8. An _____________ is a Python object that represents an error.
b. Syntax error. b. Exception. c. Logical error. d. Runtime error
9. The ____________needs to be handled by the programmer so that the program does not
terminate abruptly. ( exception)
10. When an error is encountered in a program, ______________raises or throws an
exception. (Python interpreter)
11. _________ and __________ statements are used to raise exceptions. (raise , assert)
12. An exception is caught in the_________ block and handles in _______ block. (try, except)
13. _____ error is raised if the requested file cannot be opened, or failure of I/O
operation.(IOError)
14. _____________error is raised when an identifier is not found in the local or global
namespace. ( NameError)
15. ____________error is raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.( ValueError)
16. ___________error is raised when an operation or function is attempted that is invalid for
the specified data type. ( TypeError)
17. The ________ block holds the code to be run and checked for any error, if exists. (try)
18. The exception is used to catch errors that occur when attempting to divide by zero.
(ZeroDivisionError)
19. __________ exception is raised when interpreter hits an EOF without reading any data.
(EOFError)
20. While accessing a dictionary, if the given key is not found,__________ exception is raised.
(KeyError)
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 12
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
TRUE/FALSE QUESTIONS
1. Exception and error are the same. (FALSE)
2. All types of errors can be found during compile time. (FALSE)
3. A program running properly put producing wrong output is an
exception.(FALSE)
4. Unexpected rave condition occurring during runtime which disrupts a program's execution
is an exception. (TRUE)
5.The except block deals with the exception, if it occurs. (TRUE)
6. G. try, except, finally is the correct order of blocks in exception handling. (TRUE)
7. An exception may be raised even it the program is syntactically correct. (TRUE)
Assertions and Reasons
1. Assertion (A): Exception handling handles all types of errors and exceptions.
Reasoning (R): Exception handling is responsible for handling anomalous situations during
the execution of a program.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
2. Assertion (A): Exception handling code is separate from normal code.
Reasoning (R): Program logic is different while exception handling code uses specific keywords
to handle exceptions.
1. Both A and R are true and R is the correct explanation of A.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 13
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
3. Assertion (A): Exception handling code is clear and block based in Python.
Reasoning (R): The code where unexpected runtime exception may occur is separate from the
code where the action takes place when an exception occurs.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
4. Assertion (A): No matter what exception occurs, you can always make sure that some
common action takes place for all types of exceptions.
Reasoning (R): The finally block contains the code that must execute.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 14
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Exercise Solution
Question 1
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the
statement.
Answer
A syntax error is a specific type of exception that is detected when we have not followed the
rules of the particular programming language while writing a program. On the other hand, an
exception is a Python object that represents any type of error or exceptional condition
encountered during program execution. This includes not only syntax errors but also runtime
errors and logical errors. Therefore, every syntax error is an exception but every exception
cannot be a syntax error.
Question 2
When are the following built-in exceptions raised? Give examples to support your answers.
1. ImportError
2. IOError
3. NameError
4. ZeroDivisionError
Answer
1. ImportError — It is raised when the requested module definition is not found.
Example :
from math import sqr
print(sqr(25))
Output
ImportError: cannot import name 'sqr' from 'math'import module
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 15
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Example:2
import maths
Output
ModuleNotFoundError: No module named 'maths'
2. IOError — It is raised when the file specified in a program statement cannot be opened.
Example :7
file = open("file1.txt", "r")
Output
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'
3. NameError — It is raised when a local or global variable name is not defined.
Example :
print(a+10)
Output
NameError: name 'a' is not defined.
4. ZeroDivisionError — It is raised when the denominator in a division operation is zero.
Example :
print(50/0)
Output
ZeroDivisionError: division by zero
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 16
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Question 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).
Answer
The raise statement is used to throw an exception during the execution of a program.
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Enter the numerator: 25
Enter the denominator: 5
Quotient: 5.0
Enter the numerator: 2
Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 4, in <module>
raise ZeroDivisionError("Error: Denominator cannot be zero.")
ZeroDivisionError: Error: Denominator cannot be zero.
Question 4
Use assert statement in Question No. 3 to test the division expression in the program.
Answer
numerator = float(input("Enter the numerator: "))
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 17
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
denominator = float(input("Enter the denominator: "))
assert denominator != 0, "Error: Denominator cannot be zero."
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Enter the numerator: 12
Enter the denominator: 3
Quotient: 4.0
Enter the numerator: 5
Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 3, in <module>
assert denominator != 0, "Error: Denominator cannot be zero."
AssertionError: Error: Denominator cannot be zero.
Question 5
Define the following:
1. Exception Handling
2. Throwing an exception
3. Catching an exception
Answer
1. Exception Handling — The process of writing additional code in a program to give
proper messages or instructions to the user upon encountering an exception is known as
exception handling.
2. Throwing an exception — Throwing an exception refers to the process of creating an
exception object and passing it to the runtime system or the appropriate exception
handler.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 18
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
3. Catching an exception — Catching an exception refers to the process of executing a
suitable handler or block of code specifically designed to handle that particular
exception when it occurs during program execution.
Question 6
Explain catching exceptions using try and except block.
Answer
An exception is said to be caught when a code that is designed to handle a particular exception
is executed. Exceptions, if any, are caught in the try block and 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]
Question 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")
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 19
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
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")
Answer
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both numbers entered were correct")
except ValueError: # 1 : to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # 2 : Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally: # 3 : to be executed at the end
print("JOB OVER... GO GET SOME REST")
Explanation
1. When using int(input("Enter the first number")) or int(input("Enter the second
number")), the user is expected to input an integer. If the user enters a non-integer value
(like a string or a floating-point number), a ValueError will be raised during the
conversion to an integer. The except ValueError: block is used to handle this situation by
displaying a message asking the user to enter only numbers.
2. In the line quotient = (num1 / num2), if num2 is entered as zero, it will lead to a
ZeroDivisionError during the division operation (num1 / num2). The except
ZeroDivisionError: block is used to handle this scenario by displaying a message
informing the user that the second number should not be zero.
3. The finally: block is used to define code that should be executed regardless of whether
an exception occurs or not.
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 20
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Question 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.
Answer
Note — The TypeError occurs when an incorrect number of arguments is provided for a
function, while the ValueError occurs when the number of arguments are correct but they
contain inappropriate values. Hence, in the following code TypeError is raised due to providing
an incorrect number of arguments to the math.sqrt() and math.pow() function and it is
handled using except.
import math
try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)
try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)
Output
TypeError occurred with math.pow()
TypeError occurred with math.sqrt()
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 21
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Question 9
What is the use of finally clause ? Use finally clause in the problem given in Question No. 7.
Answer
The statements inside the finally block are always executed, regardless of whether an
exception has occurred in the try block or not. It is a common practice to use the finally clause
while working with files to ensure that the file object is closed.
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
Output
Learning Exceptions...
Enter the first number: 12
Enter the second number: 4
3.0
Both numbers entered were correct
Great.. you are a good programmer
JOB OVER... GO GET SOME REST
Learning Exceptions...
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 22
EXCEL PU COLLEGE, GURVAYANAKERE
II PUC COMPUTER SCIENCE SCANNER
Enter the first number: var
Please enter only numbers
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: 33
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
MR. PRABHAKAR N.K, HOD OF COMPUTER SCIENCE 23
EXCEL PU COLLEGE, GURVAYANAKERE