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

Chapter 1 Exception Handling in Python Envr

The document provides comprehensive notes on exception handling in Python, covering topics such as syntax errors, built-in exceptions, raising exceptions, and handling exceptions using try, except, else, and finally blocks. It includes definitions, examples, and multiple choice questions to reinforce understanding. The content is structured for educational purposes at SGT PU College, Ballari.

Uploaded by

akshitar059
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)
2 views54 pages

Chapter 1 Exception Handling in Python Envr

The document provides comprehensive notes on exception handling in Python, covering topics such as syntax errors, built-in exceptions, raising exceptions, and handling exceptions using try, except, else, and finally blocks. It includes definitions, examples, and multiple choice questions to reinforce understanding. The content is structured for educational purposes at SGT PU College, Ballari.

Uploaded by

akshitar059
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

SGT PU COLLEGE, BALLARI

COMPUTER SCIENCE
II PUC PYTHON
CHAPTER 1
NOTES
EXCEPTION HANDLING
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR

Contents

LICENSE 3

CHAPTER 1: EXCEPTION HANDLING IN PYTHON 4


CHAPTER SYNOPSIS ................................................................................................................. 4
Introduction .......................................................................................................................... 4
Syntax Errors ........................................................................................................................ 4
Exceptions ............................................................................................................................ 5
Built-in Exceptions ............................................................................................................... 5
Raising Exceptions ............................................................................................................... 7
The raise Statement ............................................................................................................ 7
The assert Statement .......................................................................................................... 7
Handling Exceptions ............................................................................................................. 8
The try…except Block .................................................................................................... 10
The try..except..else Clause .................................................................................... 11
The finally clause ........................................................................................................... 12
Recovering and continuing with finally clause ................................................................ 12
MULTIPLE CHOICE QUESTIONS (MCQs)............................................................................... 13
FILL IN THE BLANKS .............................................................................................................. 34
2 MARKS QUESTIONS ............................................................................................................. 36
3 MARKS QUESTIONS ............................................................................................................. 39
5 MARKS QUESTIONS ............................................................................................................. 44
CHAPTER END EXERCISES WITH ANSWERS ....................................................................... 50

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 1: EXCEPTION HANDLING IN PYTHON

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:

Figure 2: Syntax error in Shell mode

Syntax error detected in script mode:

4
SGT PU COLLEGE, BALLARI || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR

Figure 3: Syntax Error in Script mode

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

Common Built-in Exceptions Some common built-in exceptions in Python include:

Exception Description

SyntaxError Raised when there is an error in the syntax of the code.


ValueError Raised when a built-in method or operation receives an argument with the right data
type but an inappropriate value.
IOError Raised when an input/output operation fails.
KeyboardInterrupRtaised when the user interrupts the program’s execution (usually by pressing
Ctrl+C).
ImportError Raised when an import statement fails to find the module definition.
EOFError Raised when the input() function hits an end-of-file condition.
ZeroDivisionErrorRaised when the second argument of a division or modulo operation is zero.
IndexError Raised when an index is out of range.
NameError Raised when a local or global name is not found.
IndentationError Raised when there is incorrect indentation.
TypeError Raised when an operation is applied to an object of inappropriate type.
OverflowError Raised when a calculation exceeds the maximum limit for a numeric data type.

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

We can forcefully raise an exception using the raise or assert statement.

The raise Statement

The syntax of raise statement is:


raise exception-name[(optional argument)]

raise ValueError("This is a forced exception")

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

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

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:

print("use of assert statement")


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

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.

Process of Handling Exception

• 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.

• The process of executing a suitable handler is known as catching the exception.

• 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

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:

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")

Multiple except Blocks Handling different exceptions separately.

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)

Catching All Exceptions Using a generic except clause.

try:
num = int(input("Enter a number: "))
result = 10 / num
except Exception as e:
print(f"An error occurred: {e}")

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.

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


try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)

11
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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 the division operation is", quotient)

The 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.

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 the 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 .

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:

12
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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")

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
Answer: c) Runtime 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
Answer: b) Program halts with a description of the error

3. What are syntax errors also known as?

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

4. Which Python mode provides immediate feedback on syntax 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

5. When does a ZeroDivisionError occur?

• a) Dividing by a negative number


• b) Using a zero numerator
• c) Dividing by zero
• d) Using zero in mathematical expressions
Answer: c) Dividing by zero

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
Answer: 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
Answer: a) NameError

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
Answer: b) A file that cannot be opened

9. Which exception is raised for incorrect indentation?

• a) ValueError
• b) TypeError
• c) IndentationError
• d) SyntaxError
Answer: c) IndentationError

14
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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

• a) assert
• b) raise
• c) throw
• d) except
Answer: b) raise

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
Answer: b) The current block stops execution

12. What exception does the assert statement raise if the condition is False?

• a) AssertionError
• b) ValueError
• c) SyntaxError
• d) RuntimeError
Answer: a) AssertionError

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
Answer: b) To prevent program crashes

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

• a) try
• b) except
• c) else
• d) finally
Answer: b) except

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

• 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) All are executed


• b) The first matching block is executed
• c) None are executed
• d) Only the last block is executed
Answer: b) The first matching 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
Answer: a) If no exception occurs

18. Which block comes immediately after the try block?

• a) except
• b) else
• c) finally
• d) None
Answer: a) except

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
Answer: b) To execute cleanup code

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
Answer: c) It executes regardless of exceptions

16
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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
Answer: c) ValueError

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


Answer: b) The else block executes

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


Answer: b) The program terminates

24. In a try…except block with multiple except clauses, which block is executed first?

• a) The first except block

17
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• b) The most specific matching block

• c) The last except block

• d) None of the above


Answer: b) The most specific matching block

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


Answer: b) Optional arguments like a string message

26. What does the following code output?

try:
raise ValueError("Custom error message")
except ValueError as e:
print(e)

• a) Nothing

• b) “ValueError”

• c) “Custom error message”

• d) Program terminates with error


Answer: c) “Custom error message”

27. Which exception is user-defined?

• a) ImportError

• b) ZeroDivisionError

• c) AssertionError

18
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• d) Any exception created by the programmer


Answer: 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


Answer: b) NameError occurred

29. Which exception does an assert statement raise if the expression is False?

• a) ValueError

• b) SyntaxError

• c) AssertionError

• d) NameError
Answer: c) AssertionError

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


Answer: c) Execution continues

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

19
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• a) Terminates the program immediately

• b) Searches for a handler in the call stack

• c) Ignores the exception

• d) Converts it to a warning
Answer: b) Searches for a handler in the call stack

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


Answer: a) The program terminates

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


Answer: a) Prints “Cannot divide by zero!”

34. Which statement is valid for catching exceptions?

• a) Only one except block is allowed

• b) try block can have multiple except blocks

20
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• c) No try block is needed

• d) None of the above


Answer: b) try block can have multiple except blocks

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


Answer: a) Exception handled
Finally block executed

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

• a) try

• b) except

• c) finally

• d) None of the above


Answer: c) finally

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

• a) Handle syntax errors

• b) Handle errors not specifically caught

21
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• c) Optimize performance

• d) Ignore exceptions
Answer: b) Handle errors not specifically caught

38. Which block is recommended for cleanup operations?

• a) try

• b) except

• c) finally

• d) else
Answer: c) finally

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


Answer: c) ValueError handled

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


Answer: a) The program terminates

22
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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


Answer: b) Executes if no exception occurs

42. Which block can have more than one occurrence in exception handling?

• a) try

• b) except

• c) else

• d) finally
Answer: b) except

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

23
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• d) Program terminates with ZeroDivisionError


Answer: a) Cannot divide by zero!
Execution complete.

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

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


Answer: c) Program does not crash abruptly

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


Answer: b) Clean termination or recovery

24
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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

• a) ValueError

• b) EOFError

• c) TypeError

• d) SyntaxError
Answer: b) EOFError

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


Answer: c) A calculation exceeds the max limit for a numeric type

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


Answer: c) Searching the call stack

50. What happens when an exception is successfully caught?

• a) It propagates

• b) Execution terminates

• c) Control resumes after the try block

25
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• d) None of the above


Answer: c) Control resumes after the try block

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).

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.


Answer: a) Both (A) and (R) are true, and (R) is 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).

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.

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).

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).

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.


Answer: a) Both (A) and (R) are true, and (R) is 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).

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).

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).

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.


Answer: a) Both (A) and (R) are true, and (R) is 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

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 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).

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.

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).

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).

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.

30
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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


Answer: 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.


Answer: a) Both (A) and (R) are true, and (R) is 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).

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).

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).

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.


Answer: a) Both (A) and (R) are true, and (R) is 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).

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.

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).

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).

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.


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

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.


Answer: a) Both (A) and (R) are true, and (R) is 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).

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).

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.


Answer: a) Both (A) and (R) are true, and (R) is the correct explanation of (A).

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

34
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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

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

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

2 MARKS QUESTIONS

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


Answer:

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.

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


Answer:
- 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?


Answer:
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.
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.

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


Answer:
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.


Answer:
- try...except: Used to catch and handle specific exceptions raised in the try block.

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.

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


Answer:
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?


Answer:
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?
Answer:
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.


Answer:
- 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?


Answer:
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?


Answer:
A KeyboardInterrupt 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?


Answer:
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.


Answer:
- 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.

38
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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


Answer:
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.
Answer:
OverflowError is raised when the result of a numeric operation exceeds the maximum limit for a nu-
meric type.
Example: Trying to calculate a very large exponent, such as 10**1000.
19. Explain the use of multiple except blocks.
Answer:
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?
Answer:
- 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?
Answer: It prevents abrupt termination, provides meaningful error messages, and separates error-
handling code from main logic.

3 MARKS QUESTIONS

1. Define exception handling and explain its purpose.


Answer:
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.


Answer:
- Syntax Errors:
- Occur when the code violates Python’s grammatical rules.
- Detected before the program runs (parsing stage).
- Examples: Missing colons, improper indentation.

39
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

• Exceptions:

– Occur during runtime when the code encounters an error.

– Can be handled using exception handling mechanisms.

– Examples: Division by zero, file not found.

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


Answer:
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: Raised when an operation is performed on incompatible types. Example: Adding a string
and an integer.

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


Answer:
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!")

5. Differentiate between raise and assert in Python.


Answer:
- 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".

40
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

6. What is the else clause in exception handling? Explain with an example.


Answer:
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?


Answer:
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.


Answer:
- 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.

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


Answer:
The finally block contains code that always executes, regardless of exceptions. It is often used for

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()

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


Answer:
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.
Answer:
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.


Answer:
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?


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

42
R
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON ENVR

14. Differentiate between ValueError and TypeError.


Answer:
- 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.


Answer:
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.
Answer:
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.


Answer:
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.


Answer:
IndexError occurs when trying to access an index outside the valid range of a list or sequence.
Example:

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!")

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


Answer:
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?


Answer:
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.

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.")

2. Differentiate between syntax errors and exceptions with examples.

Answer:

Feature Syntax Errors Exceptions

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

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


Answer:
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 defined. print(x) (where x is
undefined).
IndexError Accessing an invalid index in a sequence. lst = [1,2];
print(lst[5])

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


Answer:
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}")

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.

Answer:

Feature raise assert

Purpose Manually raises exceptions. Tests conditions and raises


AssertionError.
Usage Error handling logic. Debugging and validation.

46
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

Feature raise assert

Syntax raise ExceptionType("Message"). assert condition, "Message".


Example raise ValueError("Invalid assert x >= 0, "Negative
input!"). value!".

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)

Output: This is a custom exception.

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

Answer:

Feature try...except try...finally

Purpose Handles specific exceptions. Ensures cleanup code executes.

47
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

Feature try...except try...finally

Exception Yes. No.


Handling
Example Catch ZeroDivisionError. Close files regardless of exceptions.

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.")

11. Explain the finally block in Python with examples.


Answer:
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.


Answer:
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?


Answer:

48
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

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.


Answer:

Feature NameError TypeError

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".

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


Answer:
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.


Answer:
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.


Answer:
IndentationError occurs when the code is not properly indented.
Example:

if True:
print("Indentation error!") # Missing indentation raises IndentationError.

49
STUDENT NOTES || CHAPTER 1 EXCEPTION HANDLING IN PYTHON

18. Explain OverflowError with an example.


Answer:
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.


Answer:
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?


Answer:
- 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.")

CHAPTER END EXERCISES WITH ANSWERS

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")

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


Example:

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:

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.
Answer:
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}")
except AssertionError as e:
print(e)

Exercise 5: Define the following:

• 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.

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


Answer:
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")

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")

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")

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")

54

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy