Chapter 1 Exception Handling in Python Envr
Chapter 1 Exception Handling in Python Envr
COMPUTER SCIENCE
II PUC PYTHON
CHAPTER 1
NOTES
EXCEPTION HANDLING
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
Contents
LICENSE 3
2
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
LICENSE
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ or
send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
“Karnataka Second PUC Computer Science Study Material / Student Notes” by L R Mohammed Matheen
is licensed under CC BY-NC-ND 4.0.
Figure 1: Licence
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License.
Portions of this work may include material under separate copyright. These materials are not covered by
this Creative Commons license and are used by permission or under applicable copyright exceptions.
This book is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License.
3
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
CHAPTER SYNOPSIS
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 SyntaxError because of the missing closing quote.
Syntax error in interactive/shell mode:
4
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
Exceptions
Definition These are errors that occur during the execution of the program. Unlike syntax errors, excep-
tions 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.
5
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
Exception Description
Examples:
# Example of NameError
print(var + 40)
# Example of IndexError
lst = [1, 2, 3]
print(lst[5])
# Example of TypeError
print(10 +'5')
Built-in Exceptions:
6
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
A programmer can also create custom exceptions to suit one’s requirements. These are called user-defined
exceptions.
Raising Exceptions
Example:
numbers = [40,50,60,70]
length = 10
if length>len(numbers):
raise IndexError
print ("No Execution")
else:
print(length)
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
7
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
valid input. It is commonly used for debugging purposes. The syntax for assert statement is: assert
Expression[,arguments]
Example:
negativecheck(100)
negativecheck(-350)
Handling Exceptions
Exception Handling
Exception handling refers to the process of responding to the occurrence of exceptions during the execu-
tion 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.
• When an error occurs, Python interpreter creates an object called the exception object.
• This object contains information about the error like its type, file name, and position in the
program where the error has occurred.
• The object is handed over to the runtime system to find an appropriate code to handle this particular
exception.
• This process of creating an exception object and handing it over to the runtime system is called
throwing an exception.
• 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.
8
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• The runtime system searches the entire program for a block of code, called the exception handler,
that can handle the raised exception.
• 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.
• This hierarchical search in reverse order continues until the exception handler is found.
• This entire list of methods is known as the call stack.
• When a suitable handler is found in the call stack, it is executed by the runtime process.
• If the runtime system cannot find an appropriate exception after searching all the methods in the
call stack, then the program execution stops.
9
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON April 16, 2025
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:
# Code that might raise an exception
10
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
except ExceptionType:
# Code to handle the exception
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError as e:
print("Error: Division by zero -",e)
except ValueError as e:
print("Error: Invalid input - ",e)
try:
num = int(input("Enter a number: "))
result = 10 / num
except Exception as e:
print(f"An error occurred: {e}")
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.
11
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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.
Example:
In this example, the message “OVER AND OUT” will be displayed regardless of whether an exception
is raised or not .
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:
12
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• a) Logical errors
• b) Syntax errors
• c) Runtime errors
• d) Parsing errors
Answer: c) Runtime errors
• a) Runtime errors
• b) Logical errors
• c) Parsing errors
• d) None of the above
Answer: c) Parsing errors
• a) Script mode
• b) Shell mode
13
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• c) IDE mode
• d) Debug mode
Answer: b) Shell mode
• a) Continues execution
• b) Skips the error
• c) Terminates the program abruptly
• d) Jumps to exception handling code if present
Answer: d) Jumps to exception handling code if present
• a) NameError
• b) ValueError
• c) SyntaxError
• d) TypeError
Answer: a) NameError
• a) An undefined variable
• b) A file that cannot be opened
• c) A division by zero
• d) An incorrect argument type
Answer: b) A file that cannot be opened
• a) ValueError
• b) TypeError
• c) IndentationError
• d) SyntaxError
Answer: c) IndentationError
14
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• a) assert
• b) raise
• c) throw
• d) except
Answer: b) raise
11. What happens after an exception is raised using the raise statement?
12. What exception does the assert statement raise if the condition is False?
• a) AssertionError
• b) ValueError
• c) SyntaxError
• d) RuntimeError
Answer: a) AssertionError
• a) try
• b) except
• c) else
• d) finally
Answer: b) except
• a) try
• b) except
15
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• c) else
• d) finally
Answer: d) finally
16. What happens if multiple except blocks are present for a single try block?
• a) If no exception occurs
• b) If an exception occurs
• c) Always executed
• d) Never executed
Answer: a) If no exception occurs
• a) except
• b) else
• c) finally
• d) None
Answer: a) except
16
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
• a) ZeroDivisionError
• b) SyntaxError
• c) ValueError
• d) TypeError
Answer: c) ValueError
23. What will happen if an exception not matched by any except block occurs?
24. In a try…except block with multiple except clauses, which block is executed first?
17
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
25. What can be included in the raise statement for additional information?
try:
raise ValueError("Custom error message")
except ValueError as e:
print(e)
• a) Nothing
• b) “ValueError”
• a) ImportError
• b) ZeroDivisionError
• c) AssertionError
18
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
try:
raise NameError("Example")
except NameError:
print("NameError occurred")
• a) NameError
• b) NameError occurred
• c) Example
29. Which exception does an assert statement raise if the expression is False?
• a) ValueError
• b) SyntaxError
• c) AssertionError
• d) NameError
Answer: c) AssertionError
• b) An exception is raised
• c) Execution continues
19
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• d) Converts it to a warning
Answer: b) Searches for a handler in the call stack
• c) Execution continues
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
20
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
try:
print(1 / 0)
except ZeroDivisionError:
print("Exception handled")
finally:
print("Finally block executed")
• a) Exception handled
Finally block executed
• a) try
• b) except
• c) finally
21
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• c) Optimize performance
• d) Ignore exceptions
Answer: b) Handle errors not specifically caught
• a) try
• b) except
• c) finally
• d) else
Answer: c) finally
try:
int("abc")
except ValueError:
print("ValueError handled")
• a) ValueError
• b) Program terminates
• c) ValueError handled
• b) It continues execution
22
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• a) It is mandatory
42. Which block can have more than one occurrence in exception handling?
• a) try
• b) except
• c) else
• d) finally
Answer: b) except
try:
result = 50 / int(input("Enter a number: "))
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
finally:
print("Execution complete.")
• b) Invalid input!
Execution complete.
• c) 50 divided by 0
23
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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
Answer: a) ValueError
• a) Better syntax
24
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• a) ValueError
• b) EOFError
• c) TypeError
• d) SyntaxError
Answer: b) EOFError
• a) Raising an exception
• b) Catching an exception
• a) It propagates
• b) Execution terminates
25
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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).
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).
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).
26
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
54. Assertion (A): A ZeroDivisionError is raised when a division operation involves a denomina-
tor 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).
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).
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).
57. Assertion (A): The try block must be followed by at least one except block.
27
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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).
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).
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).
60. Assertion (A): The else block in a try...except structure executes only if no exception occurs
28
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING 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).
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).
62. Assertion (A): A ValueError is raised when an invalid data type is passed to a function or
operation.
Reason (R): The ValueError 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).
63. Assertion (A): The raise statement can be used to throw both built-in and user-defined excep-
29
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
tions.
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).
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).
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).
30
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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).
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).
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).
31
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
b) Both Assertion (A) and Reason (R) are true, but (R) is not 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).
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).
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.
32
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING 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).
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).
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).
74. Assertion (A): The IndentationError exception is raised when code is not properly indented
in Python.
33
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING 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).
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).
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
34
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
10. The statement is used in Python to test conditions and raise an AssertionError if
the condition evaluates to False.
Answer: assert
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
18. The Python runtime system searches the to find an appropriate handler for the
raised exception.
Answer: call stack
35
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
19. A(n) exception occurs when an index is out of the valid range of a sequence.
Answer: IndexError
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. The method or block of code responsible for responding to a specific type of exception is called
a(n) .
Answer: exception handler
28. Python’s standard library includes numerous exceptions to handle commonly oc-
curring errors.
Answer: built-in
30. The try block is mandatory when using the clause in Python exception handling.
Answer: except
2 MARKS QUESTIONS
36
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
- 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.
Answer:
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?
Answer:
The finally block in Python is used to execute code that must always run, regardless of whether an ex-
ception occurs or not. It is typically used for cleanup operations like closing files or releasing resources.
6. List two examples of built-in exceptions in Python and when they occur.
Answer:
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.
37
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
- 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.
38
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
3 MARKS QUESTIONS
39
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• Exceptions:
try:
result = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
• assert:
40
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
try:
result = int("abc")
except ValueError:
print("Invalid number!")
except:
print("Some other error occurred.")
• try...finally:
41
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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()
try:
result = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
try:
raise ValueError("Custom error message")
except ValueError as e:
print(e)
42
R
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
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.
Answer:
The assert statement tests a condition and raises an AssertionError if the condition is false.
Example:
x = -1
assert x >= 0, "Negative number!"
try:
while True:
data = input()
except EOFError:
print("End of file reached.")
43
R
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR
try:
lst = [1, 2, 3]
print(lst[5])
except IndexError:
print("Index out of range!")
try:
import non_existent_module
except ImportError:
print("Module not found.")
5 MARKS QUESTIONS
1. What is Exception Handling? Explain its need and process with examples.
Answer:
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:
44
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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.")
Answer:
Definition Errors in the structure of the code. Errors occurring during program
execution.
Detection Detected during compilation (parsing Detected during runtime.
phase).
Fixability Must be fixed before running the code. Can be handled using exception
handling.
Examples Missing colons, incorrect indentation. Division by zero, accessing undefined
files.
Example Code print("Hello" (missing )) 5 / 0 raises ZeroDivisionError.
3. Explain the role of the try, except, and finally blocks with examples.
Answer:
- 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 opera-
tions.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution complete.")
45
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Division successful: {result}")
Output Scenarios:
1. For input 5, it prints: Division successful: 2.0.
2. For input 0, it prints: Cannot divide by zero!.
Answer:
46
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
7. How are exceptions raised and caught in Python? Explain the call stack.
Answer:
- Raising Exceptions: Python raises exceptions when runtime errors occur (e.g., dividing by zero). Pro-
grammers can raise exceptions manually using the raise statement.
- Catching Exceptions: Exceptions are handled using try...except blocks. Python matches the ex-
ception 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.
Answer:
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)
Answer:
47
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
10. What is the purpose of a generic except block? Explain with an example.
Answer:
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.")
48
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
When it Occurs Variable is used before being defined. Operation is applied to an incorrect
type.
Example print(x) (where x is undefined). 5 + "hello".
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.")
if True:
print("Indentation error!") # Missing indentation raises IndentationError.
49
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
try:
import non_existent_module
except ImportError:
print("Module not found.")
Exercise 1: Justify the statement: “Every syntax error is an exception but every exception cannot
be a syntax error.”
Answer:
Syntax errors are mistakes in the code’s structure or grammar, such as missing colons or incorrect inden-
tation, which prevent the code from being parsed. They are caught before the program runs and must
50
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
be fixed for the program to execute. Exceptions, on the other hand, occur during the execution of syn-
tactically 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 Answer: 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 Answer: 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")
try:
print(nonexistent_variable)
except NameError:
print("Variable not defined")
• d) ZeroDivisionError Answer: Raised when the second argument of a division or modulo oper-
ation 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.
51
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON April 16, 2025
Answer:
The raise statement is used to explicitly trigger an exception in the code.
Example Code:
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.
Answer:
Example Code with assert:
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 AssertionError as e:
print(e)
• a) Exception Handling
Answer: 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
Answer: Throwing an exception means explicitly triggering an exception in a program using the
raise statement.
52
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
• c) Catching an Exception
Answer: Catching an exception means detecting and responding to an exception using try and
except blocks.
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")
else:
print("Great .. you are a good programmer")
53
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON
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.
Answer:
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.
Answer:
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")
else:
print("Great .. you are a good programmer")
54