Chapter1_ExceptionHandling
Chapter1_ExceptionHandling
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.
sl
no Exception Description Example Output
II PUC-SJRPUCW Page 2
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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)
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.
II PUC-SJRPUCW Page 5
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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)
II PUC-SJRPUCW Page 8
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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.
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
II PUC-SJRPUCW Page 12
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
II PUC-SJRPUCW Page 13
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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
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
II PUC-SJRPUCW Page 15
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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
29. Which exception does an assert statement raise if the expression is False?
a) ValueError b) SyntaxError c) AssertionError d) NameError
42. Which block can have more than one occurrence in exception handling?
a) try b) except c) else d) finally
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
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)
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.
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)
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)
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)
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.
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.
II PUC-SJRPUCW Page 30
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
3 MARKS QUESTIONS
II PUC-SJRPUCW Page 32
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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!"
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!")
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.")
II PUC-SJRPUCW Page 36
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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.")
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!.
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.
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.")
try:
f = open("file.txt", "r")
except FileNotFoundError:
print("File not found.")
finally: print("Cleaning up resources.")
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)
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")
II PUC-SJRPUCW Page 42
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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.
Example Code:
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)
II PUC-SJRPUCW Page 44
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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.
II PUC-SJRPUCW Page 46
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
II PUC-SJRPUCW Page 47
II PUC Chapter – 1 Exception Handling in Python (New NCERT Syllabus)
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)
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)
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”
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")
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)
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