[go: up one dir, main page]

0% found this document useful (0 votes)
17 views54 pages

Chapter1_ExceptionHandling

The document discusses exception handling in Python, explaining the types of errors (syntax, runtime, and logical) and how to manage them using try, except, finally, and else blocks. It details built-in exceptions, user-defined exceptions, and the process of raising and catching exceptions. Additionally, it includes multiple choice questions to test understanding of exception handling concepts.

Uploaded by

grstationery20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views54 pages

Chapter1_ExceptionHandling

The document discusses exception handling in Python, explaining the types of errors (syntax, runtime, and logical) and how to manage them using try, except, finally, and else blocks. It details built-in exceptions, user-defined exceptions, and the process of raising and catching exceptions. Additionally, it includes multiple choice questions to test understanding of exception handling concepts.

Uploaded by

grstationery20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

CHAPTER 1: EXCEPTION HANDLING IN PYTHON


Introduction :
When there are syntax errors, runtime errors or logical errors in the code, program does not
execute at all or the program executes but generates unexpected output or behaves
abnormally.
Exception handling in Python allows a programmer to deal with runtime errors, ensuring that
the program continues to operate in the presence of unexpected conditions. This process
involves identifying, catching, and handling exceptions to maintain the normal flow of the
program.

Syntax Errors :
Definition: Syntax errors occur when the code written does not conform to the rules of the
Python language. These errors are detected during the parsing stage and must be fixed before
the program can run. Syntax errors are also called parsing errors.

Example:
marks = 10
if marks>20:
print "GOOD SCORE!"

This code will produce a Syntax Error because of the missing parenthesis in print statement.

Exceptions: “AN EXCEPTION IS A PYTHON OBJECT THAT REPRESENTS AN ERROR”.


Definition : These are errors that occur during the execution of the program. Unlike syntax
errors, exceptions are detected during runtime and can be handled using exception handlers.
Examples include trying to open a file that does not exist or dividing a number by zero.
Example: result = 10 / 0

Built-in Exceptions : Commonly occurring exceptions are usually defined in the


compiler/interpreter. These are called built-in exceptions. Some common built-in exceptions
( K E N T Z O V IM IN IN IO S ) in Python include:
II PUC-SJRPUCW Page 1
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

sl
no Exception Description Example Output

Raised when there is marks =20


Syntax
1
Error
an error in the syntax if marks>10
of the code. print "good"

Raised when a built-


in method or
operation receives an
a="hello"
2 Value Error argument with the
right data type but int(a)
an inappropriate
value.
Raised when an try:
input/output
operation fails and f=open("student.txt",'r')
3 IO Error when the file print(f.read()) file not found
specified in a f.close()
program statement except IOError:
cannot be opened. print('file not found')
Raised when the user
interrupts the
Keyboard
4 program’s execution
Interrupt
(usually by pressing
Ctrl+C).
Raised when an
import statement
5 Import Error
fails to find the
module definition.
Raised when the
input() function hits
6 EOF Error
an end-of-file
condition.

II PUC-SJRPUCW Page 2
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Raised when the a=10


Zero second argument of b=0
7 Division
Error a division or modulo c=a/b
operation is zero. print(c)
Raised when an index list = [1, 2, 3]
8 Index Error
is out of range. print(list[5])
Raised when a local
print(var + 40)
9 Name Error or global name is not
found.
Raised when there is
Indentation
10 incorrect
Error
indentation.
Raised when an
operation is applied
11 Type Error print(10 +'5')
to an object of
inappropriate type.
Raised when a
calculation exceeds n=999.999
Overflow
12 the maximum limit for i in range (1,100):
Error
for a numeric data n=n**10
type.

USERDEFINED EXCEPTIONS: A programmer can also create custom exceptions to suit one’s
requirements. These are called user-defined exceptions.

Raising Exceptions :
• We can forcefully raise(THROW) an exception using the raise or assert statement.
• 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 of execution of program
and jumping to that part of the program(exception handler code) which is written to
handle such exceptional situations.

1. The raise Statement :
The syntax of raise statement is:
raise exception-name[(optional argument)]
Example1: raise ValueError("This is a forced exception")
II PUC-SJRPUCW Page 3
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Example2:
numbers = [40,50,60,70]
length = 10
if length>len(numbers):
raise IndexError
print ("No Execution")
else:
print(length)

2. The assert Statement :


The assert statement is used to test expressions and raise an AssertionError if the expression
is false. This statement is generally used in the beginning of the function or after a function
call to check for valid input. It is commonly used for debugging purposes.

The syntax for assert statement is: assert expression[,arguments]


Example:
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print (negativecheck(100) )
print(negativecheck(-350) )

II PUC-SJRPUCW Page 4
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Handling Exceptions
Exception Handling : Exception handling refers to the process of responding to the
occurrence of exceptions during the execution of a program. This is typically done using try,
except, finally, and else blocks in Python.

Need for Exception Handling:-


• Essential to prevent program crashes by capturing and managing run time errors.
• Separates main program logic from error detection and correction code.
• The compiler/interpreter tracks the exact error location.
• Applicable to both user-defined and built-in exceptions.

Process of Handling Exception


1. When an error occurs, Python interpreter creates an object called the exception object.
2. This object contains information about the error like its type, file name, and position in
the program where the error has occurred.
3. The object is handed over to the runtime system to find an appropriate code to handle
this particular exception.
4. This process of creating an exception object and handing it over to the runtime system is
called throwing an exception.
5. When an exception occurs while executing a particular program statement, the control
jumps to an exception handler, abandoning the execution of the remaining program
statements.
6. The runtime system searches the entire program for a block of code, called the
exception handler, that can handle the raised exception.
7. The runtime system first searches the method in which the error occurred and the
exception was raised. If not found, it searches the method from which this method was
called.
8. This hierarchical search in reverse order continues until the exception handler is found.

II PUC-SJRPUCW Page 5
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

9. This entire list of methods is known as the call stack.


10. When a suitable handler is found in the call stack, it is executed by the runtime process.
11. The process of executing a suitable handler is known as catching the exception.
12. If the runtime system cannot find an appropriate exception after searching all the
methods in the call stack, then the program execution stops.

CATCHING EXCEPTIONS:
1. The try…except Block
The try...except block is used to handle exceptions in Python. Code that might raise an
exception is placed inside the try block, and the handling of the exception is done in the except
block.
try:
Syntax: # Code that might raise an exception
except ExceptionType:
# Code to handle the exception

II PUC-SJRPUCW Page 6
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Example1:
print("Practicing for try block")
try:
numerator = 50
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")

II PUC-SJRPUCW Page 7
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Multiple except Blocks: Handling different exceptions separately.


Example:
print ("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")

II PUC-SJRPUCW Page 8
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

USE OF EXCEPT WITHOUT SPECIFYING AN EXCEPTION: Catching All


Exceptions Using a generic except clause
Example:
print ("Handling exceptions without naming them")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully")
except ValueError:
print ("Only INTEGERS should be entered")
except:
print(" OOPS.....SOME EXCEPTION RAISED")

II PUC-SJRPUCW Page 9
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

2. try...except…else clause
The try..except..else Clause :
We can put an additional else clause to the normal try...except. Code
inside the else block will run if no exceptions are raised in the try block.

Example Program: Use of else clause


print ("Handling exception using try...except...else")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
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)

II PUC-SJRPUCW Page 10
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

3. Finally clause : The finally clause is an optional part of the try statement
in Python. The code inside the finally block is always executed, regardless of
whether an exception occurred or not. It is typically used for cleanup actions, like
closing files or releasing resources.

II PUC-SJRPUCW Page 11
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

In this example, the message “OVER AND OUT” will be displayed regardless of whether an
exception is raised or not

Recovering and continuing with finally clause


If an error has been detected in the try block and the exception has been thrown, the
appropriate except block will be executed to handle the error. But if the exception is not
handled by any of the except clauses, then it is re-raised after the execution of the finally
block.
Example

print("Handling exception using try...except...else...finally")


try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:

II PUC-SJRPUCW Page 12
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

print("The result of the division operation is", quotient)


finally:
print("OVER AND OUT")

II PUC-SJRPUCW Page 13
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

MULTIPLE CHOICE QUESTIONS (MCQs)

1. What type of errors are exceptions in Python?


a) Logical errors b) Syntax errors c) Runtime errors d) Parsing errors

2. What happens when a syntax error occurs in Python?


a) Program continues with incorrect output
b) Program halts with a description of the error
c) Program fixes the error automatically
d) Program warns but does not stop

3. What are syntax errors also known as?


a) Runtime errors b) Logical errors c) Parsing errors d) None of the above

4. Which Python mode provides immediate feedback on syntax errors ?


a) Script mode b) Shell mode c) IDE mode d) Debug mode

5. When does a Zero Division Error occur?


a) Dividing by a negative number b) Using a zero numerator
c) Dividing by zero d) using zero in mathematical expressions

6. What does Python do when an exception is raised during execution?


a) Continues execution b) Skips the error
c) Terminates the program abruptly d) Jumps to exception handling code if present

7. Which exception is raised when a variable is not defined?


a) NameError b) ValueError c) SyntaxError d) TypeError

8. What does the IOError exception indicate?


a) An undefined variable b) A file that cannot be opened
c) A division by zero d) an incorrect argument type

9. Which exception is raised for incorrect indentation?


a) ValueError b) TypeError c) IndentationError d) SyntaxError

10. Which keyword is used to manually raise an exception?


a) assert b) raise c) throw d) except

II PUC-SJRPUCW Page 14
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

11. What happens after an exception is raised using the raise statement?
a) The remaining statements in the block are executed
b) The current block stops execution
c) Execution continues in the same block
d) None of the above

12. What exception does the assert statement raise if the condition is False?
a) AssertionError b) ValueError c) SyntaxError d) RuntimeError

13. What is the main purpose of exception handling?


a) To debug syntax errors b) To prevent program crashes
c) To increase execution speed d) To optimize performance

14. Which block is used to catch exceptions in Python?


a) try b) except c) else d) finally

15. Which block is always executed, irrespective of whether an exception occurred?


a) try b) except c) else d) finally

16. What happens if multiple except blocks are present for a single try block?
a) All are executed b) The first matching block is executed
c) None are executed d) Only the last block is executed

17. When is the else clause executed in a try…except block?


a) If no exception occurs b) If an exception occurs
c) Always executed d) Never executed

18. Which block comes immediately after the try block?


a) except b) else c) finally d) None

19. What is the primary use of the finally block?


a) To catch specific exceptions b) To execute cleanup code
c) To handle syntax errors d) To ensure program optimization

20. Which statement is true for the finally block?


a) It executes only if an exception occurs b) It executes only if no exception occurs
c) It executes regardless of exceptions d) It does not execute under any condition

II PUC-SJRPUCW Page 15
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

21. Which exception is handled in the following code?


try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
a) ZeroDivisionError b) SyntaxError c) ValueError d) TypeError

22. What happens if no exception is raised in the try block?


a) The except block executes b) The else block executes
c) Both except and else blocks execute d) The program terminates
23. What will happen if an exception not matched by any except block occurs?
a) The program continues b) The program terminates
c) The last except block is executed d) none of the above
24. In a try…except block with multiple except clauses, which block is executed first?
a) The first except block b) the most specific matching block
c) The last except block d) none of the above

25. What can be included in the raise statement for additional information?
a) Exception name only b) Optional arguments like a string message
c) Exception handling code d) None of the above
26. What does the following code output?
try:
raise ValueError("Custom error message")
except ValueError as e:
print(e)
a) Nothing b) “Value Error”
c) “Customerror message” d) Program terminates with error

27. Which exception is user-defined?


a) ImportError b) Zero Division Error
c) AssertionError d) Any exception created by the programmer

28. What is printed by the following code?


try:
raise NameError("Example")
except NameError:
print("NameError occurred")
a) NameError b) NameError occurred c) Example d) none of the above
II PUC-SJRPUCW Page 16
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

29. Which exception does an assert statement raise if the expression is False?
a) ValueError b) SyntaxError c) AssertionError d) NameError

30. What happens if the assert condition evaluates to True?


a) The program halts b) An exception is raised
c) Execution continues d) The next except block is executed

31. What does the runtime system do when an exception occurs?


a) Terminates the program immediately b) Searches for a handler in the call stack
c) Ignores the exception d) converts it to a warning

32. What happens if no handler is found in the call stack?


a) The program terminates b) The exception is ignored
c) Execution continues d) The exception is logged but execution continues

33. What does the following code do?


try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero!")
a) Prints “Cannot divide by zero!” b) Terminates with ZeroDivisionError
c) Ignores the error d) None of the above

34. Which statement is valid for catching exceptions?


a) Only one except block is allowed b) try block can have multiple except blocks
c) No try block is needed d) none of the above

35. What is the output of the following code?


try:
print(1 / 0)
except ZeroDivisionError:
print("Exception handled")
finally: print("Finally block executed")
a) Exception handled Finally block executed b) Finally block executed
c) Program terminates with ZeroDivisionError d) None of the above

36. Which block will execute even if an exception is not raised?


a) try b) except c) finally d) None of the above
II PUC-SJRPUCW Page 17
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

37. What is the purpose of a generic except block?


a) Handle syntax errors b) Handle errors not specifically caught
c) Optimize performance d) Ignore exceptions

38. Which block is recommended for cleanup operations?


a) try b) except c) finally d) else

39. What does the following code print?


try:
int("abc")
except ValueError:
print("ValueError handled")
a) ValueError b) Program terminates c) ValueError handled d) None of the above

40. What happens when an exception is raised but not caught?


a) The program terminates b) It continues execution
c) It enters the finally block and resumes d) None of the above

41. What is the purpose of an else clause in a try block?


a) It is mandatory b) Executes if no exception occurs
c) Always executes regardless of exceptions d) It defines error recovery steps

42. Which block can have more than one occurrence in exception handling?
a) try b) except c) else d) finally

43. What is the output of the following code if the input is 0?


try:
result = 50 / int(input("Enter a number: "))
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
finally: print("Execution complete.")

a) Cannot divide by zero! Execution complete. b) Invalid input! Execution complete.


c) 50 divided by 0 d) Program terminates with ZeroDivisionError

II PUC-SJRPUCW Page 18
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

44. Which exception is raised if the following code is executed and the input is abc?
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
a) ValueError b) TypeError c) SyntaxError d) NameError

45. What does exception handling ensure?


a) Errors are ignored b) Code runs faster
c) Program does not crash abruptly d) Syntax errors are corrected automatically

46. What is the primary benefit of a try…finally structure?


a) Better syntax b) Clean termination or recovery
c) Handling specific exceptions d) Ignoring runtime errors

47. What exception is raised if input() encounters EOF?


a) ValueError b) EOFError c) TypeError d) SyntaxError

48. When is the OverFlowError raised?


a) A file cannot be opened
b) Division by zero occurs
c) A calculation exceeds the max limit for a numeric type
d) An undefined variable is accessed

49. What is the process of finding an exception handler called?


a) Raising an exception b) Catching an exception
c) Searching the call stack d) None of the above

50. What happens when an exception is successfully caught?


a) It propagates b) Execution terminates
c) Control resumes after the try block d) None of the above

51. Assertion (A): Syntax errors are detected during the execution of a Python program.
Reason (R): Syntax errors occur when the rules of the programming language are
violated.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
II PUC-SJRPUCW Page 19
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

c) (A) is true, but (R) is false.


d) (A) is false, but (R) is true.
Answer: c) (A) is true, but (R) is false.

52. Assertion (A): Exceptions disrupt the normal flow of program execution.
Reason (R): Exceptions represent errors that occur during runtime and must be handled.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

53. Assertion (A): Built-in exceptions in Python handle commonly occurring errors.
Reason (R): Programmers need to create user-defined exceptions for all error cases.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

54. Assertion (A): A ZeroDivisionError is raised when a division operation involves a


denominator of zero.
Reason (R): Python checks for runtime errors during program execution.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

55. Assertion (A): The raise statement in Python can be used to manually raise exceptions.
Reason (R): The raise statement forces an exception to be raised and handled.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

II PUC-SJRPUCW Page 20
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

56. Assertion (A): The assert statement raises an exception if the given condition is false.
Reason (R): The assert statement is used for debugging and testing in Python.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

57. Assertion (A): The try block must be followed by at least one except block.
Reason (R): The try block allows execution of code that may raise exceptions, while the
except block handles them.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

58. Assertion (A): The finally block is executed only when an exception is raised in the try
block.
Reason (R): The finally block ensures cleanup code is executed regardless of whether an
exception occurred or not.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: d) (A) is false, but (R) is true.

59. Assertion (A): Multiple except blocks can be used for a single try block.
Reason (R): Each except block handles a specific type of exception.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

II PUC-SJRPUCW Page 21
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

60. Assertion (A): The else block in a try...except structure executes only if no exception
occurs in the try block.
Reason (R): The else block is executed before the finally block.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

61. Assertion (A): If an exception is not caught in the except block, the program terminates.
Reason (R): Unhandled exceptions propagate up the call stack until a handler is found.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

62. Assertion (A): A Value Error is raised when an invalid data type is passed to a function or
operation.
Reason (R): The Value Error exception occurs for both invalid data types and invalid
values.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

63. Assertion (A): The raise statement can be used to throw both built-in and user-defined
exceptions.
Reason (R): The raise statement interrupts the normal flow of the program and jumps to
the exception handler.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of (A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

II PUC-SJRPUCW Page 22
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

64. Assertion (A): The assert statement allows developers to write test conditions directly in
the code.
Reason (R): If the condition in an assert statement evaluates to False, an AssertionError is
raised.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of (A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

65. Assertion (A): The try block handles exceptions, while the except block identifies
exceptions.
Reason (R): The try block contains code that might raise exceptions, while the except
block defines handlers for exceptions.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of (A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

66. Assertion (A): An EOFError is raised when the input() function reaches the end of a file
without receiving any input.
Reason (R): The EOFError occurs when the Python program encounters an empty input
stream unexpectedly.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of (A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

67. Assertion (A): The finally block is executed even if an unhandled exception occurs in the
try block.
Reason (R): The finally block is designed to perform cleanup operations regardless of the
program’s state.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

II PUC-SJRPUCW Page 23
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

68. Assertion (A): The Python interpreter automatically searches the call stack to find an
appropriate exception handler when an exception is raised.
Reason (R): If an exception handler is not found in the call stack, the program terminates
with a traceback.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

69. Assertion (A): The TypeError exception is raised when an operation is applied to an
object of an inappropriate type.
Reason (R): Python performs type-checking at runtime for all operations.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

70. Assertion (A): A generic except block can be used to catch any exception that is not
explicitly named in previous except blocks.
Reason (R): A generic except block should always be placed after all specific except
blocks to avoid masking exceptions.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of (A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.
Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

71. Assertion (A): The try...except...else structure ensures that the else block is executed
only if the try block executes without raising an exception.
Reason (R): The else block in exception handling is useful for executing code that must
run only when no exceptions occur.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of (A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

II PUC-SJRPUCW Page 24
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

72. Assertion (A): The NameError exception is raised when a variable is referenced before it
is defined.
Reason (R): Undefined variables in Python automatically default to None.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

73. Assertion (A): Exception handling in Python can be applied to both built-in and user-
defined exceptions.
Reason (R): Python provides the raise statement to throw exceptions and the try...except
block to handle them.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

74. Assertion (A): The IndentationError exception is raised when code is not properly
indented in Python.
Reason (R): Python enforces indentation as part of its syntax for defining blocks of code.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

75. Assertion (A): Exception handling improves program robustness and user experience.
Reason (R): Exception handling prevents programs from crashing abruptly during
runtime errors.
a) Both Assertion (A) and Reason (R) are true, and (R) is the correct explanation of (A).
b) Both Assertion (A) and Reason (R) are true, but (R) is not the correct explanation of
(A).
c) (A) is true, but (R) is false.
d) (A) is false, but (R) is true.

II PUC-SJRPUCW Page 25
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

FILL IN THE BLANKS


1. A________ error occurs when the rules of the programming language are not followed.
Answer: Syntax
2. Errors that occur during program execution and disrupt its normal flow are
called________. Answer: Exceptions
3. The ________ block in Python is used to catch exceptions and handle them
appropriately. Answer: except
4. A division by zero operation raises the ________ exception. Answer: ZeroDivisionError
5. The ________ exception is raised when a variable is referenced but has not been
defined. Answer: NameError
6. The Python statement used to manually raise an exception is ________. Answer: raise
7. A________ block is always executed, regardless of whether an exception occurred or
not. Answer: finally
8. The ________ exception occurs when the file specified in a program cannot be opened.
Answer: IOError
9. The process of identifying and handling exceptions is called ________. Answer:
Exception handling
10. The ________ statement is used in Python to test conditions and raise an AssertionError
if the condition evaluates to False. Answer: assert
11. A block of code suspected to raise exceptions is enclosed within a ________ block.
Answer: try
12. A(n)________exception can be created by programmers to handle specific errors not
covered by built-in exceptions. Answer: user-defined
13. The exception raised when an input operation hits the end of the file without reading
any data is ________. Answer: EOFError
14. Python provides a structured block of text, known as ________, that contains
information about the sequence of function calls during an exception. Answer:
traceback
15. The ________ clause in Python is executed only if the try block completes successfully
with out any exceptions. Answer: else
16. A(n) ________ exception is raised when an invalid value is passed to a built-in method
or operation. Answer: ValueError
17. The exception raised due to incorrect indentation in Python is ________. Answer:
IndentationError
18. The Python runtime system searches the ________ to find an appropriate handler for
the raised exception. Answer: call stack
19. A(n) ________ exception occurs when an index is out of the valid range of a sequence.
Answer: IndexError
II PUC-SJRPUCW Page 26
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

20. The process of identifying a suitable handler for a raised exception is called ________
the exception. Answer: catching
21. The exception raised when the requested module is not found is ________. Answer:
ImportError
22. The exception raised when a key is not found in a dictionary is ________. Answer:
KeyError
23. The exception raised when a calculation exceeds the maximum limit for a numeric type
is ________. Answer: OverflowError
24. The ________ block is placed after a try block to handle multiple exceptions using
separate handlers. Answer: except
25. When no specific handler is defined for an exception, a generic ________ block can be
used. Answer: except
26. The exception raised when the user presses an interrupt key like Ctrl+C is ________.
Answer: KeyboardInterrupt
27. Themethodorblockofcoderesponsibleforrespondingtoaspecifictypeofexceptioniscalled
a(n) ________. Answer: exception handler
28. Python’s standard library includes numerous ________ exceptions to handle commonly
occurring errors. Answer: built-in
29. When an exception occurs, the normal flow of the program is ________. Answer:
interrupted
30. The try block is mandatory when using the ________ clause in Python exception
handling. Answer: except

II PUC-SJRPUCW Page 27
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

2MARKS : QUESTION & ANSWERS:

1. What is the difference between syntax errors and exceptions?


• Syntax errors are detected when the code does not follow the grammatical rules
of Python. These errors are also known as parsing errors and prevent the program
from running until fixed.
• Exceptions occur during the execution of a program when something goes wrong,
such as dividing by zero, opening a non-existent file, etc. Exceptions can be
handled to prevent the program from crashing.

2. Define the term exception in Python.


An exception in Python is an error that disrupts the normal flow of execution. It occurs
during runtime and is represented as an object. Python raises exceptions when it
encounters errors that it cannot handle automatically. The programmer must handle
these exceptions to prevent the program from terminating abnormally.

3. What does the finally block do in Python?


The finally block in Python is used to execute code that must always run, regardless of
whether an exception occurs or not. It is typically used for cleanup operations like
closing files or releasing resources.

4. Differentiate between the raise and assert statements in Python.


• raise is used to manually raise an exception in Python. It can raise both built-in
and user-defined exceptions.
• assert is used to test an expression. If the expression evaluates to False, it raises
an AssertionError. It is primarily used for debugging purposes to check conditions
in code

5. What is the purpose of the try block in exception handling?


The try block is used to enclose code that might raise an exception. It allows the
program to attempt to run the code and pass control to the corresponding except block
if an exception is encountered.

6. List two examples of built-in exceptions in Python and when they occur
1. ZeroDivisionError: Raised when dividing a number by zero.
2. ValueError: Raised when an operation or function receives an argument of the right type
but an inappropriate value.

II PUC-SJRPUCW Page 28
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

7. What is an EOFError, and when does it occur?


An EOFError occurs when the input() function reaches the end of a file (EOF) without
reading any data. It happens when there is no more data to read, such as in an empty
input stream.

8. Differentiate between try...except and try...finally blocks.


• try...except: Used to catch and handle specific exceptions raised in the try block
• try...finally: The finally block is always executed, regardless of whether an exception
occurred in the try block. It is often used for cleanup operations.

9. Explain the purpose of the else clause in exception handling.


The else clause is executed only if no exception is raised in the try block. It is used to run
code that should only execute when the try block is successful and no exceptions occur.

10. What happens if an exception is not caught in a program?


If an exception is not caught, it propagates up the call stack. If no handler is found, the
program will terminate, and a traceback will be displayed, indicating where the
exception occurred.

11. What is a traceback in Python?


A traceback is a structured block of text displayed when an exception is raised. It
provides information about the sequence of function calls leading to the exception,
helping in debugging the program.

12. Differentiate between NameError and TypeError.


NameError: Raised when a variable is used before being defined.
TypeError: Raised when an operation is applied to an object of an inappropriate type,
such as adding a string to an integer.

13. What is the purpose of a generic except block?


A generic except block is used to catch any exception that is not explicitly handled by
the previous except blocks. It is a fallback mechanism for unanticipated errors.

14. When is a KeyboardInterrupt exception raised?


A Keyboard Interrupt exception is raised when the user interrupts the program’s
execution by pressing Ctrl+C or another interrupt key.

15. How does the finally block ensure cleanup operations?


II PUC-SJRPUCW Page 29
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

The finally block ensures that cleanup operations, like closing files or releasing
resources, are always executed regardless of whether an exception was raised or not.

16. Distinguish between IOError and ImportError.


IOError: Raised when an input/output operation (e.g., file opening) fails.
ImportError: Raised when Python cannot find or load a module that was imported.

17. What is the purpose of the call stack in exception handling?


The call stack is a list of function calls made during program execution. When an
exception occurs, Python searches the call stack to find an appropriate exception
handler.

18. Define OverflowError and provide an example.


OverflowError is raised when the result of a numeric operation exceeds the maximum
limit for a numeric type. Example: Trying to calculate a very large exponent, such as
10**1000.

19. Explain the use of multiple except blocks.


Multiple except blocks allow handling different types of exceptions in a single try block.
Each block can be tailored to handle a specific exception raised by the try block.

20. How does Python differentiate between exceptions and syntax errors?
• Exceptions occur during the program’s execution when an error is encountered
(e.g., division by zero).
• Syntax errors occur when the code violates the rules of Python’s grammar and
must be fixed before execution.

21. Why is exception handling important?


It prevents abrupt termination, provides meaningful error messages, and separates
error handling code from main logic.

II PUC-SJRPUCW Page 30
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

3 MARKS QUESTIONS

1. Define exception handling and explain its purpose.


Exception handling is the process of responding to runtime errors (exceptions) in a
program to prevent abrupt termination. Its purpose is to:
• Capture and address runtime errors.
• Allow the program to continue functioning after an error.
• Separate the main logic from error
• handling code using constructs like try, except, and finally.

2. Differentiate between syntax errors and exceptions in Python.


Syntax Errors Exceptions:
Occur when the code violates Python’s Occur during runtime when the code
grammatical rules encounters an error.
Detected before the program runs Can be handled using exception handling
(parsing stage).- mechanisms.
Examples: Missing colons, improper Examples: Division by zero, file not found
indentation

3. What are built-in exceptions? List any three with examples.


Built-in exceptions are pre-defined errors in Python’s standard library that handle
common runtime issues.
Examples include:
1. ZeroDivisionError: Raised when dividing by zero. Example: 5 / 0.
2. NameError: Raised when referencing an undefined variable. Example: print(x) (where
x is not defined).
3. TypeError: Raisedwhenanoperationis performed onincompatible types. Example:
Adding a string and an integer.

4. Explain the try...except block with an example.


A try...except block is used to catch and handle exceptions in Python.
• try block: Contains code that might raise an exception.
• except block: Contains code to handle specific exceptions.
Example:
try:
result = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
II PUC-SJRPUCW Page 31
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

5. Differentiate between raise and assert in Python.


• raise:- Used to manually raise exceptions.
- Syntax: raise ExceptionType("Message").
• assert:– Used to test a condition. If the condition is false, it raises an
AssertionError.
Syntax: assert condition, "Message"
6. What is the else clause in exception handling? Explain with an example.
The else clause in a try...except block runs only if no exception occurs in the try block.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)

7. What is a generic except block? When is it used?


A generic except block catches any exception not explicitly handled by other except
blocks.
Use Case:
- To handle unexpected exceptions.
- It should be placed after all specific except blocks.
Example:
try:
result = int("abc")
except ValueError:
print("Invalid number!")
except:
print("Some other error occurred.")

8. Differentiate between try...except and try...finally blocks.


• try...except:- Handles exceptions raised in the try block.- Example: Handling
division by zero or invalid input.
• try...finally:– Ensures the finally block runs regardless of whether an exception
occurred.– Used for cleanup operations.

II PUC-SJRPUCW Page 32
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

9. Explain the purpose of the finally block with an example.


The finally block contains code that always executes, regardless of exceptions. It is often
used for resource cleanup.
Example:
try:
f = open("file.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Closing the file.")
f.close()

10. What is the role of the call stack in exception handling?


The call stack is a sequence of function calls made during program execution. When an
exception occurs:
- Python searches the call stack for an appropriate exception handler.
- If no handler is found, the program terminates, displaying a traceback.

11. Explain ZeroDivisionError with an example.


ZeroDivisionError is raised when dividing a number by zero.
Example:
try:
result = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

12. Describe the raise statement with an example.


The raise statement is used to manually trigger exceptions in Python.
Example:
try:
raise ValueError("Custom error message")
except ValueError as e:
print(e)

13. What is a traceback? What information does it provide?


A traceback is a detailed error message displayed when an exception occurs. It provides:
- The sequence of function calls leading to the error.
II PUC-SJRPUCW Page 33
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

- The type of exception raised.


- The line of code where the exception occurred.

14. Differentiate between ValueError and TypeError.


• ValueError: Raised when a function receives an argument of the correct type but
an inappropriate value (e.g., int("abc")).
• TypeError: Raised when an operation is applied to an object of an incorrect type
(e.g., adding a string to an integer).

15. Explain user-defined exceptions with an example.


User-defined exceptions allow programmers to create custom error types using classes.
Example:
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception.")
except CustomError as e:
print(e)

16. What is the purpose of the assert statement? Explain with an example.
The assert statement tests a condition and raises an AssertionError if the condition is
false.
Example:
x =-1
assert x >= 0, "Negative number!"

17. What is EOFError? Explain with an example.


EOFError is raised when the input() function hits the end of a file without reading any
data.
Example:
try:
while True:
data = input()
except EOFError:
print("End of file reached.")

18. Explain IndexError with an example.

II PUC-SJRPUCW Page 34
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

IndexError occurs when trying to access an index outside the valid range of a list or
sequence.
Example
try:
lst = [1, 2, 3]
print(lst[5])
except IndexError:
print("Index out of range!")

19. When is an ImportError raised? Provide an example.


ImportError occurs when a module cannot be imported.
Example:
try:
import non_existent_module
except ImportError:
print("Module not found.")

20. How does Python handle uncaught exceptions?


If an exception is not caught using a handler, Python:
1. Searches the call stack for a handler.
2. Terminates the program if no handler is found.
3. Displays a traceback showing the sequence of calls leading to the exception.

II PUC-SJRPUCW Page 35
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

5 MARKS QUESTIONS

1. What is Exception Handling? Explain its need and process with examples.
Exception handling is the process of managing runtime errors in a program to prevent
abrupt termination and ensure proper error recovery.
Need:
1. To capture and handle runtime errors gracefully.
2. To provide meaningful feedback to the user.
3. To ensure proper cleanup of resources.
Process:
1. Throwing Exceptions: When an error occurs, Python creates an exception object and
transfers control to the runtime system.
2. Catching Exceptions: The runtime searches for an appropriate exception handler in
the call stack.
3. Handling Exceptions: The matched handler executes specific code to resolve the
error.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Division by zero is not allowed.")
except ValueError:
print("Invalid input! Please enter an integer.")

2. Differentiate between syntax errors and exceptions with examples.

Feature Syntax Errors Exceptions


Definition Errors in the structure of the Errors occurring during program
code. execution
Detection Detected during compilation Detected during runtime
(parsing phase).
Must be fixed before running Can be handled using exception
Fixability the code. handling
Missing colons, incorrect Division by zero, accessing
Examples indentation undefined files.

II PUC-SJRPUCW Page 36
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Example print("Hello" (missing )) 5 / 0 raises ZeroDivisionError.


Code

3. Explain the role of the try, except, and finally blocks with examples.
• try block: Contains code that may raise exceptions.
• except block: Catches and handles specific exceptions raised in the try block.
• finally block: Executes code regardless of whether an exception occurred, used for
cleanup operations.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution complete.")

4. Describe the use of built-in exceptions in Python with examples.


Built-in exceptions are predefined in Python to handle common runtime errors:
Exception When it Occurs Example
ZeroDivisionError Dividing a number by zero. 10 / 0
ValueError Invalid argument for a function. int("abc")
NameError Referencing a variable that is not print(x) (where x is
defined undefined).
IndexError Accessing an invalid index in a lst = [1,2]; print(lst[5])
sequence.

5. Explain the else clause in Python exception handling with an example.


The else clause executes only if no exception occurs in the try block.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Division successful: {result}")

II PUC-SJRPUCW Page 37
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Output Scenarios:
1. For input 5, it prints: Division successful: 2.0.
2. For input 0, it prints: Cannot divide by zero!.

6. Differentiate between raise and assert in Python with examples


Feature raise assert
Purpose Manually raises exceptions. Tests conditions and raises
AssertionError
Usage Error handling logic. Debugging and validation.
Syntax raise ExceptionType("Message"). assert condition, "Message"
Example raise ValueError("Invalid assert x >= 0, "Negative value!".
input!").

7. How are exceptions raised and caught in Python? Explain the call stack.
Raising Exceptions: Python raises exceptions when runtime errors occur (e.g., dividing
by zero). Programmers can raise exceptions manually using the raise statement.-
Catching Exceptions: Exceptions are handled using try...except blocks. Python matches
the exception type with available handlers.
Call Stack: The call stack is a sequence of function calls made during execution. If an
exception is raised, Python searches the call stack for a matching handler. If no handler
is found, the program terminates with a traceback.

8. Explain user-defined exceptions with an example.


User-defined exceptions allow programmers to create custom error types.
Example:
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception.")
except CustomError as e:
print(e)

Output: This is a custom exception.

9. Differentiate between try...except and try...finally


Feature try...except try...finally
Purpose Handles specific exceptions. Ensures cleanup code executes.
Exception Handling Yes No
II PUC-SJRPUCW Page 38
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Syntax
Example Catch ZeroDivisionError Close files regardless of exceptions
10. What is the purpose of a generic except block? Explain with an example.
The generic except block handles all exceptions not explicitly specified in other except
blocks.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
except:
print("An error occurred.")

11. Explain the finally block in Python with examples.


The finally block contains code that always executes, even if an exception occurs.
Example:

try:
f = open("file.txt", "r")
except FileNotFoundError:
print("File not found.")
finally: print("Cleaning up resources.")

12. What is EOFError? Explain its significance with an example.


EOFError occurs when the input() function encounters an unexpected end of file.
Example:
try:
data = input("Enter data: ")
except EOFError:
print("No more input available.")

13. How does Python handle uncaught exceptions?


If an exception is not caught:
1. Python searches the call stack for a handler.
2. If no handler is found, the program terminates.
3. A traceback is displayed, showing where the exception occurred.

14. Differentiate between NameError and TypeError.


II PUC-SJRPUCW Page 39
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Feature Name Error Type Error


When it Variable is used before being Operation is applied to an
occurs defined. incorrect type
Example print(x) (where x is undefined). 5 + "hello"

15. What is the traceback in Python, and what does it include?


A traceback is a detailed error message displayed when an exception occurs. It includes:
1. The sequence of function calls leading to the error.
2. The exception type raised.
3. The line of code where the exception occurred.

16. Explain multiple except blocks with an example.


Multiple except blocks handle different exception types separately.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid integer.")

17. What is the IndentationError exception? Provide an example.


IndentationError occurs when the code is not properly indented.
Example:
if True:
print("Indentation error!") # Missing indentation raises IndentationError.

18. Explain OverflowError with an example.


OverflowError is raised when a numerical operation exceeds the maximum
representable limit.
Example:
try:
result = 10 ** 1000
except OverflowError:
print("Result is too large.")

19. Describe ImportError with an example.


II PUC-SJRPUCW Page 40
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

ImportError is raised when Python cannot find or load a module.


Example:
try:
import non_existent_module
except ImportError:
print("Module not found.")

20. How do try, except, and finally work together?


try block: Runs code that might raise exceptions.
except block: Handles exceptions raised in the try block.
finally block: Executes code regardless of exceptions, often used for cleanup.

Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution complete.")

II PUC-SJRPUCW Page 41
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

CHAPTER END EXERCISES WITH ANSWERS

Exercise 1: Justify the statement: “Every syntax error is an exception but every exception
cannot be a syntax error.”
Syntax errors are mistakes in the code’s structure or grammar, such as missing colons
or incorrect indentation, which prevent the code from being parsed. They are caught
before the program runs and must be fixed for the program to execute. Exceptions, on
the other hand, occur during the execution of syntactically correct code when
something unexpected happens, like trying to divide by zero. Thus, while all syntax
errors are exceptions (as they represent issues to be corrected), not all exceptions are
syntax errors; Some are runtime issues that arise despite correct syntax.

Exercise 2: When are the following built-in exceptions raised? Give examples.
a) ImportError: Raised when an import statement fails to find the module definition or
when a from …import fails to find a name that is to be imported.
Example:
try:
import nonexistent_module
except ImportError:
print("Module not found")

b) IOError: Raised when an input/output operation fails, such as the file not being
found or disk full.
Example:
try:
file = open('nonexistent_file.txt', 'r')
except IOError:
print("File not found")

c) NameError : Raised when a local or global name is not found.


Example:
try:
print(nonexistent_variable)
except NameError:
print("Variable not defined")

II PUC-SJRPUCW Page 42
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

d) ZeroDivisionError : Raised when the second argument of a division or modulo


operation is zero.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

Exercise 3: What is the use of a raise statement? Write a code to accept two numbers and
display the quotient. Raise an exception if the denominator is zero.

The raise statement is used to explicitly trigger an exception in the code.

Example Code:

def divide(a, b):


if b == 0:
raise ZeroDivisionError("Denominator cannot be zero")
return a / b
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = divide(num1, num2)
print(f"The quotient is: {result}")
except ZeroDivisionError as e:
print(e)

Exercise 4: Use assert statement in the previous code to test the division expression.
Example Code with assert:
def divide(a, b):
assert b != 0, "Denominator cannot be zero"
return a / b
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = divide(num1, num2)
print(f"The quotient is: {result}")

II PUC-SJRPUCW Page 43
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

except AssertionError as e:
print(e)

Exercise 5: Define the following:


a) Exception Handling : Exception handling refers to the process of responding to the
occurrence of exceptions– anomalous or exceptional conditions requiring special processing–
during the execution of a program. This is typically done using try, except, finally, and else
blocks in Python.
b) Throwing an Exception : Throwing an exception means explicitly triggering an exception in a
program using the raise statement.
c) Catching an Exception: Catching an exception means detecting and responding to an
exception using try and except blocks.

Exercise 6: Explain catching exceptions using try and except block.


In Python, exceptions are caught using try and except blocks. The code that might raise an
exception is placed inside the try block, and the code to handle the exception is placed inside
the except block. If an exception occurs, the control is transferred to the except block, skipping
the rest of the code in the try block.
Example:
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
result = numerator / denominator
print(f"The result is: {result}")
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter a valid integer")

Exercise 7: Fill in the blanks in the code.


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 ValueError: # to enter only integers
print("Please enter only numbers")

II PUC-SJRPUCW Page 44
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

except ZeroDivisionError: # Denominator should not be zero


print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
finally: # to be executed at the end
print("JOB OVER... GO GET SOME REST")

Exercise 8: Write a code using the math module where you use the wrong number of
arguments for a method and handle the ValueError exception.

import math
try:
result = math.sqrt(16, 2) # Incorrect number of arguments
except TypeError:
print("Incorrect number of arguments provided to sqrt() method")

Exercise 9: What is the use of finally clause? Use finally clause in the problem given in
Exercise 7.

The finally clause is used to execute a block of code no matter whether an exception was
raised or not. It is typically used to release external resources (like files or network
connections) regardless of how the previous blocks exit.
Example with finally clause from Exercise 7:
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 ValueError: # to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
finally: # to be executed at the end
print("JOB OVER... GO GET SOME REST")
II PUC-SJRPUCW Page 45
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

****************
Chapter 1 : Exception Handling in Python : VV IMP QA:

1. What is a syntax error? How does interpreter respond when it encounters syntax error?
• Syntax errors occur when we have not followed the rules of a the particular
programming language while writing program.
• Syntax errors are also called as Parsing errors.
• It generally gives brief explanation about error and a suggestion to rectify it.
• On encountering syntax errors ,Interpreter doesnot execute the program unless
we rectify the error.

2. Define Exception. What is exception handling?


• Exceptions are errors that occur at runtime when the program is being executed
• “AN EXCEPTION IS A PYTHON OBJECT THAT REPRESENTS AN ERROR”.
• Definition : These are errors that occur during the execution of the program.
Unlike syntax errors, exceptions are detected during runtime and can be handled
using exception handlers. Examples include trying to open a file that does not
exist or dividing a number by zero.
• Example: result = 10 / 0
Exception Handling : Exception handling refers to the process of responding to
the occurrence of exceptions during the execution of a program. This is typically
done using try, except, finally, and else blocks in Python.
• Process of resolving errors that occurs in a program
• Catching exceptions, what caused them, and then responding.

3. Explain built-in exceptions in detail.


Commonly occurring exceptions are usually defined in the compiler/interpreter. These
are called built-in exceptions. ( K E N T Z O V IM IN IN IO S )
sl Exception Description Example Output

II PUC-SJRPUCW Page 46
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Raised when there is an marks =20


Syntax
1 error in the syntax of if marks>10
Error
the code. print "good"

Raised when a built-in


method or operation
Value receives an argument a="hello"
2
Error with the right data type int(a)
but an inappropriate
value.
Raised when an try:
input/output operation f=open("student.txt",'r')
fails and when the file print(f.read())
3 IO Error
specified in a program f.close() file not found
statement cannot be except IOError:
opened. print('file not found')
Raised when the user
interrupts the
Keyboard
4 program’s execution Ctrl + c
Interrupt
(usually by pressing
Ctrl+C).
Raised when an import
Import
5 statement fails to find Import pick Import pickle
Error
the module definition.
Raised when the input()
6 EOF Error function hits an end-of-
file condition.
Raised when the second a=10
Zero
argument of a division b=0
7 Division
or modulo operation is c=a/b
Error
zero. print(c)
Index Raised when an index is list = [1, 2, 3]
8
Error out of range. print(list[5])

II PUC-SJRPUCW Page 47
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Raised when a local or


Name print(var + 40)
9 global name is not
Error
found.
a,b=10,20
if a>b: Expected an indent block
Indentati Raised when there is
10 print(a) after if statement
on Error incorrect indentation.
else:
print(b)
Raised when an
Type operation is applied to
11 print(10 +'5')
Error an object of
inappropriate type.
Raised when a
n=999.999
Overflow calculation exceeds the
12 for i in range (1,100):
Error maximum limit for a
n=n**10
numeric data type.

4. Explain need for exception handling.


• Exception handling is being used not only in Python programming but in most
programming languages like C++, Java, Ruby, etc.
• It is a useful technique that helps in capturing runtime errors and handling them so
as to avoid the program getting crashed. Following are some
1. Python categorizes exceptions into distinct types so that specific exception handlers
(code to handle that particular exception) can be created for each type.
2. 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.
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.

5. Explain process of handling exception or steps in exception handling process.

II PUC-SJRPUCW Page 48
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

1. When an error occurs, Python interpreter creates an object called the exception
object.
2. This object contains information about the error like its type, file name and position
in the program where the error has occurred.
3. The object is handed over to the runtime system so that it can find an appropriate
code to handle this particular exception.
4. This process of creating an exception object and handing it over to the runtime
system is called throwing an exception.
5. It is important to note that when an exception occurs while executing a particular
program statement, the control jumps to an exception handler, abandoning
execution of the remaining program statements.
6. The runtime system searches the entire program for a block of code, called the
exception handler that can handle the raised exception.
7. It first searches for the method in which the error has occurred and the exception
has been raised.
8. If not found, then it searches the method from which this method (in which
exception was raised) was called.
9. This hierarchical search in reverse order continues till the exception handler is found.
10. This entire list of methods is known as call stack.
11. When a suitable handler is found in the call stack, it is executed by the runtime
process.
12. This process of executing a suitable handler is known as catching the exception.
13. 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.
Steps of handling exception

II PUC-SJRPUCW Page 49
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

6. Explain assert statement with syntax and example.


• An assert statement in Python is used to test an expression in the program code.
• It will check if a condition is TRUE, otherwise for FALSE it raises error
• 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]
• On encountering an assert statement, Python evaluates the expression given
immediately after the assert keyword.
• If this expression is false, an AssertionError exception is raised which can be
handled like any other exception.
Example of assert statement
1) x=5

II PUC-SJRPUCW Page 50
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

assert x>0 #no error


assert x<0 #error

2) def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))

• In the code, the assert statement checks for the value of the variable number.
• In case the number gets a negative value, AssertionError will be thrown, and
subsequent statements will not be executed.
• Hence, on passing a negative value (-350) as an argument, it results in
AssertionError and displays the message “OOPS…. Negative Number”

7) Explain raise with syntax and example


• Programmers can also forcefully raise exceptions in a program using the raise and
assert statements.
• Raise is used to rasie an error manually .

Syntax of raise Statement : raise exception-name[(optional argument)]


Example1: raise ValueError("This is a forced exception")
Example2:
numbers = [40,50,60,70]
length = 10
if length>len(numbers):
raise IndexError
print ("No Execution")
else:
print(length)

8) Explain try and except block with syntax and example.


• Try is used to test a block of code for errors.
• The try...except block is used to handle exceptions in Python.
• Code that might raise an exception is placed inside the try block, and the
handling of the exception is done in the except block.

Syntax: try:
II PUC-SJRPUCW # Code that might raise an exception Page 51
except ExceptionType:
# Code to handle the exception
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

Example1:
try:
numerator = 50
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")

9) Explain multiple except clauses with syntax and example.


Multiple except Blocks: Handling different exceptions separately with many
except clauses.
Example:
print ("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
10) Explain try exception else clause with example.
• else is used if no error occurs in try block.
• We can put an additional else clause to the normal try...except. Code inside the
else block will run if no exceptions are raised in the try block.
Example :
print ("Handling exception using try...except...else")
try:
numerator=50
denom=int(input("Enter the denominator: "))
II PUC-SJRPUCW Page 52
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

quotient=(numerator/denom)
print ("Division performed successfully")
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)

11) Explain finally clause with syntax and example.


• Finally clause is an optional part of the try statement in Python. Runs whether an error
occurs or not.
• The code inside the finally block is always executed, regardless of whether an exception
occurred or not.
• It is typically used for cleanup actions, like closing files or releasing resources.
Example:
print ("Handling exception using try...except...else...finally")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
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)
finally:
print ("OVER AND OUT")
In this example, the message “OVER AND OUT” will be displayed regardless of whether an
exception is raised or not

12) Explain recovering and continuing with finally clause with example.
Recovering and continuing with finally clause
If an error has been detected in the try block and the exception has been thrown, the
appropriate except block will be executed to handle the error. But if the exception is not

II PUC-SJRPUCW Page 53
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)

handled by any of the except clauses, then it is re-raised after the execution of the
finally block.
Example
print("Handling exception using try...except...else...finally")
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:
print("The result of the division operation is", quotient)
finally:
print("OVER AND OUT")

*******

II PUC-SJRPUCW Page 54

You might also like