Exception Handling in Python
Haryana Board · Class 12 · Computer Science
NCERT Solutions for Exception Handling in Python — Haryana Board Class 12 Computer Science.
Interactive on Super Tutor
Studying Exception Handling in Python? Get the full interactive chapter.
Quizzes, flashcards, AI doubt-solver and a step-by-step study plan — built for ncert solutions and more.
1,000+ Class 12 students started this chapter today

This is just one of 11+ visuals inside Super Tutor's Exception Handling in Python chapter
Explore the full setEXERCISE — Exception Handling in Python
1"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.Show solution
Justification:
Part 1 — Every syntax error is an exception:
In Python, syntax errors are treated as a special type of exception called `SyntaxError`. When the Python interpreter encounters code that violates the grammatical rules of the language (e.g., missing colon, incorrect indentation), it raises a `SyntaxError` exception. Thus, every syntax error is indeed an exception.
Example:
```python
if x = 5: # SyntaxError: invalid syntax
print(x)
```
Here Python raises: `SyntaxError: invalid syntax`
Part 2 — Every exception cannot be a syntax error:
Exceptions are a much broader category. Many exceptions occur at runtime (during execution) even when the code is syntactically correct. These are called runtime exceptions or logical exceptions and have nothing to do with syntax rules.
Examples:
- `ZeroDivisionError` — occurs when a number is divided by zero (syntax is correct).
- `ValueError` — occurs when a function receives an argument of the correct type but inappropriate value.
- `NameError` — occurs when a variable is used before being defined.
```python
a = 10
b = 0
print(a / b) # ZeroDivisionError — syntax is perfectly correct
```
Conclusion: Since syntax errors form only a subset of all possible exceptions, every syntax error is an exception, but every exception cannot be a syntax error. Hence the statement is justified.
2When are the following built-in exceptions raised? Give examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionErrorShow solution
When raised: `ImportError` is raised when the `import` statement fails to find the module being imported, or when a name cannot be imported from a module.
Example:
```python
import mathematics # No such module exists
```
Output:
```
ModuleNotFoundError: No module named 'mathematics'
```
(Note: `ModuleNotFoundError` is a subclass of `ImportError`.)
Another example:
```python
from math import squareroot # 'squareroot' does not exist in math
```
Output:
```
ImportError: cannot import name 'squareroot' from 'math'
```
---
b) IOError
When raised: `IOError` (also known as `OSError` in Python 3) is raised when an input/output operation fails. Common causes include trying to open a file that does not exist, or lacking permission to read/write a file.
Example:
```python
f = open("nonexistent_file.txt", "r") # File does not exist
```
Output:
```
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
```
(Note: `FileNotFoundError` is a subclass of `IOError`/`OSError`.)
---
c) NameError
When raised: `NameError` is raised when a local or global variable (name) is referenced but has not been defined or assigned any value.
Example:
```python
print(total) # 'total' has not been defined anywhere
```
Output:
```
NameError: name 'total' is not defined
```
---
d) ZeroDivisionError
When raised: `ZeroDivisionError` is raised when the second operand (divisor/denominator) in a division or modulo operation is zero.
Example:
```python
a = 10
b = 0
result = a / b # Division by zero
print(result)
```
Output:
```
ZeroDivisionError: division by zero
```
3What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).Show solution
The `raise` statement is used to explicitly raise (throw) an exception in a program. It allows the programmer to force a specific exception to occur when a certain condition is met, even if Python would not raise it automatically. It is useful for enforcing constraints and validating inputs.
Syntax:
```python
raise ExceptionType("message")
```
Code:
```python
try:
num1 = int(input("Enter the first number (numerator): "))
num2 = int(input("Enter the second number (denominator): "))
if num2 == 0:
raise ZeroDivisionError("Denominator cannot be zero!")
quotient = num1 / num2
print("Quotient =", quotient)
except ZeroDivisionError as e:
print("Error:", e)
except ValueError:
print("Please enter valid integer numbers only.")
```
Sample Output 1 (valid input):
```
Enter the first number (numerator): 10
Enter the second number (denominator): 2
Quotient = 5.0
```
Sample Output 2 (denominator = 0):
```
Enter the first number (numerator): 10
Enter the second number (denominator): 0
Error: Denominator cannot be zero!
```
Explanation:
- If `num2` is 0, the `raise` statement explicitly raises a `ZeroDivisionError` with a custom message.
- The `except` block catches this exception and displays the error message without crashing the program.
4Use assert statement in Question No. 3 to test the division expression in the program.Show solution
Syntax:
```python
assert condition, "Error message"
```
Code using assert:
```python
try:
num1 = int(input("Enter the first number (numerator): "))
num2 = int(input("Enter the second number (denominator): "))
assert num2 != 0, "Denominator cannot be zero!"
quotient = num1 / num2
print("Quotient =", quotient)
except AssertionError as e:
print("AssertionError:", e)
except ValueError:
print("Please enter valid integer numbers only.")
```
Sample Output 1 (valid input):
```
Enter the first number (numerator): 15
Enter the second number (denominator): 3
Quotient = 5.0
```
Sample Output 2 (denominator = 0):
```
Enter the first number (numerator): 15
Enter the second number (denominator): 0
AssertionError: Denominator cannot be zero!
```
Explanation:
- `assert num2 != 0` checks that the denominator is not zero.
- If `num2 == 0`, the assertion fails and Python raises `AssertionError` with the message "Denominator cannot be zero!".
- The `except AssertionError` block catches and displays this error gracefully.
5Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exceptionShow solution
Exception handling is the process of writing additional code in a program to deal with runtime errors (exceptions) gracefully, so that the program does not terminate abruptly. It involves:
- Detecting the occurrence of an error.
- Transferring control to a special block of code called the exception handler.
- Displaying meaningful messages to the user and allowing the program to continue or terminate cleanly.
In Python, exception handling is implemented using `try`, `except`, `else`, and `finally` blocks.
---
b) Throwing an Exception:
When an error occurs during the execution of a program, the Python interpreter creates an exception object containing information about the error (its type, file name, and position in the program). The process of creating this exception object and handing it over to the runtime system is called throwing (or raising) an exception.
This can happen:
- Automatically — when Python detects a runtime error (e.g., division by zero).
- Explicitly — when the programmer uses the `raise` or `assert` statement.
---
c) Catching an Exception:
An exception is said to be caught when the code specifically designed to handle that particular exception (the exception handler) is executed. In Python, exceptions are caught inside the `except` block that follows the `try` block. When the runtime system finds a matching `except` handler in the call stack, it executes that handler — this process is called catching the exception.
Example:
```python
try:
x = 10 / 0 # Exception is thrown here
except ZeroDivisionError: # Exception is caught here
print("Cannot divide by zero")
```
6Explain catching exceptions using try and except block.Show solution
In Python, the `try` and `except` blocks are used together to detect and handle exceptions.
Syntax:
```python
try:
# statements that may cause an exception
except ExceptionType1:
# handler for ExceptionType1
except ExceptionType2:
# handler for ExceptionType2
else:
# executed if no exception occurs (optional)
finally:
# always executed (optional)
```
Working / Flow of Execution:
1. The statements that are likely to cause an error are placed inside the `try` block.
2. If an exception occurs in the `try` block, Python immediately stops executing the remaining statements in that block and looks for a matching `except` clause.
3. If a matching `except` clause is found, the code inside that `except` block (the exception handler) is executed.
4. If no exception occurs, the `else` block (if present) is executed.
5. The `finally` block (if present) is always executed regardless of whether an exception occurred or not.
6. If no matching `except` handler is found, the exception propagates up the call stack.
Example:
```python
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
except ValueError:
print("Error: Please enter integers only.")
except ZeroDivisionError:
print("Error: Denominator cannot be zero.")
else:
print("Result =", result)
finally:
print("Execution complete.")
```
Sample Output (ZeroDivisionError):
```
Enter numerator: 10
Enter denominator: 0
Error: Denominator cannot be zero.
Execution complete.
```
Sample Output (no exception):
```
Enter numerator: 10
Enter denominator: 2
Result = 5.0
Execution complete.
```
Key Points:
- Multiple `except` clauses can be written to handle different types of exceptions.
- A single `except` clause without a specific exception type will catch all exceptions.
- The `else` block runs only when no exception is raised in the `try` block.
- The `finally` block always runs, making it useful for cleanup operations (e.g., closing files).
7Consider the code given below and fill in the blanks.
```python
print ("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both the numbers entered were correct")
except __________ : # to enter only integers
print("Please enter only numbers")
except __________ : # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
__________ : # to be executed at the end
print("JOB OVER... GO GET SOME REST")
```Show solution
Filled Code:
```python
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")
```
Explanation of blanks filled:
| Blank | Filled With | Reason |
|---|---|---|
| First `except` | `ValueError` | When the user enters a non-integer (e.g., a string), `int()` raises a `ValueError`. |
| Second `except` | `ZeroDivisionError` | When `num2` is 0, dividing by it raises a `ZeroDivisionError`. |
| Last blank | `finally` | The `finally` clause is always executed at the end, regardless of whether an exception occurred or not. |
Sample Output (non-integer input):
```
Learning Exceptions...
Enter the first number: abc
Please enter only numbers
JOB OVER... GO GET SOME REST
```
Sample Output (denominator = 0):
```
Learning Exceptions...
Enter the first number: 10
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
```
Sample Output (valid input):
```
Learning Exceptions...
Enter the first number: 10
Enter the second number: 2
Both the numbers entered were correct
Great .. you are a good programmer
JOB OVER... GO GET SOME REST
```
8You have learnt how to use math module in Class XI. Write a code where you use the wrong number of arguments for a method (say sqrt() or pow()). Use the exception handling process to catch the ValueError exception.Show solution
Code:
```python
import math
try:
# Passing a negative number to sqrt() causes ValueError
number = float(input("Enter a number to find its square root: "))
result = math.sqrt(number)
print("Square root of", number, "is", result)
except ValueError:
print("ValueError: Cannot compute square root of a negative number.")
except TypeError:
print("TypeError: Wrong type of argument passed to the function.")
else:
print("Operation completed successfully.")
finally:
print("Program execution finished.")
```
Sample Output 1 (valid input):
```
Enter a number to find its square root: 25
Square root of 25.0 is 5.0
Operation completed successfully.
Program execution finished.
```
Sample Output 2 (negative number — ValueError):
```
Enter a number to find its square root: -9
ValueError: Cannot compute square root of a negative number.
Program execution finished.
```
Explanation:
- `math.sqrt(-9)` raises a `ValueError` because the square root of a negative number is not a real number.
- The `except ValueError` block catches this exception and displays a meaningful message.
- The `finally` block always executes, indicating the program has finished.
Additional Example using pow() with wrong argument type:
```python
import math
try:
result = math.pow("four", 2) # Passing a string instead of a number
print(result)
except TypeError as e:
print("TypeError caught:", e)
except ValueError as e:
print("ValueError caught:", e)
```
Output:
```
TypeError caught: must be real number, not str
```
9What is the use of finally clause? Use finally clause in the problem given in Question No. 7.Show solution
The `finally` clause is an optional block used with `try`-`except`. Its key characteristics are:
1. The code inside the `finally` block is always executed, regardless of whether an exception occurred in the `try` block or not.
2. It is executed even if there is no matching `except` handler for the raised exception.
3. It is typically used for cleanup operations such as closing files, releasing resources, or displaying a closing message.
4. Unlike the `except` block, the `finally` block does not terminate the exception — if an unhandled exception exists, it continues to propagate after the `finally` block executes.
Code for Question 7 with finally clause:
```python
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:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
```
Sample Output 1 (ValueError — non-integer input):
```
Learning Exceptions...
Enter the first number: hello
Please enter only numbers
JOB OVER... GO GET SOME REST
```
Sample Output 2 (ZeroDivisionError):
```
Learning Exceptions...
Enter the first number: 10
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
```
Sample Output 3 (No exception):
```
Learning Exceptions...
Enter the first number: 10
Enter the second number: 2
Both the numbers entered were correct
Great .. you are a good programmer
JOB OVER... GO GET SOME REST
```
Key Observation: In all three cases, the `finally` block executes and prints `"JOB OVER... GO GET SOME REST"`, demonstrating that the `finally` clause always runs irrespective of the outcome of the `try` block.
Stuck on a step?
Ask Super Tutor AI to explain any solution on this page in a simpler way — free, 24x7.
Ask a Doubt FreeFrequently Asked Questions
What are the important topics in Exception Handling in Python for Haryana Board Class 12 Computer Science?
How to score full marks in Exception Handling in Python — Haryana Board Class 12 Computer Science?
Where can I get free NCERT Solutions for Exception Handling in Python Class 12 Computer Science?
Sources & Official References
Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.
More resources for Exception Handling in Python
Important Questions
Practice with board exam-style questions
Syllabus
What topics to cover
Revision Notes
Key points for last-minute revision
Study Plan
Step-by-step plan to ace this chapter
Flashcards
Quick-fire cards for active recall
Formula Sheet
All formulas in one place
Chapter Summary
Understand the chapter at a glance
Practice Quiz
Test yourself with a quick quiz
Concept Maps
See how topics connect visually
For serious students
Get the full Exception Handling in Python chapter — for free.
Quizzes, flashcards, AI doubt-solver and a step-by-step study plan for Haryana Board Class 12 Computer Science.