Skip to main content
Chapter 1 of 13
NCERT Solutions

Exception Handling in Python — NCERT Solutions

Tripura Board · Class 12 · Computer Science

NCERT Solutions for Exception Handling in Python, Tripura Board Class 12 Computer Science: 9 textbook questions solved step by step.

45 questions76 flashcards2 formulas & key relations5 concepts

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.

Free trial, no card needed.

An infographic comparing Syntax Errors, Runtime Errors (Exceptions), and Logical Errors in Python, highlighting their characteristics, detection time, and impact on program execution.
Super Tutor

Learn better with visuals Super Tutor pairs illustrations like this with notes and quizzes for Exception Handling in Python.

9 Questions Solved · 1 Section

The first 5 solutions are open to read. The other 4 are free with a Super Tutor account.

EXERCISE — Exception Handling in Python

1"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.Show solution

Given concept: Relationship between syntax errors and exceptions in Python.

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:

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.
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) ZeroDivisionError
Show solution

a) ImportError

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:

import mathematics   # No such module exists

Output:

ModuleNotFoundError: No module named 'mathematics'

(Note: ModuleNotFoundError is a subclass of ImportError.)

Another example:

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:

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:

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:

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

Use of raise statement:
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:

raise ExceptionType("message")

Code:

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

Concept: The assert statement is used to test a condition. If the condition is True, execution continues normally. If the condition is False, Python raises an AssertionError with an optional message.

Syntax:

assert condition, "Error message"

Code using assert:

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 exception
Show solution

a) Exception Handling:

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:

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.

Free with a Super Tutor account

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

Free with a Super Tutor account

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.

Free with a Super Tutor account

9What is the use of finally clause? Use finally clause in the problem given in Question No. 7.

Free with a Super Tutor account

4 more solved questions in Exception Handling in Python

They are free with a Super Tutor account, along with practice quizzes and flashcards for this chapter. Free to start, no card needed.

Frequently Asked Questions

What are the important topics in Exception Handling in Python for Tripura Board Class 12 Computer Science?
Key topics in Exception Handling in Python include Core Ideas, Built-in Exceptions, Raising Exceptions, Handling Exceptions. Study these first, then practise questions on each for the Tripura Board Class 12 board exam.
Are these NCERT Solutions for Exception Handling in Python free?
The first 5 of the 9 solutions on this page are open to read. The other 4 are free with a Super Tutor account — signing up is free and needs no card.
How should I revise Exception Handling in Python for the Tripura Board Class 12 board exam?
Learn the core ideas first, then work through the 45 practice questions on Exception Handling in Python. Revise definitions regularly and use flashcards for quick recall before the exam.

Sources & Official References

Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.

For serious students

Get the full Exception Handling in Python chapter — start free.

Quizzes, flashcards, an AI doubt solver and a study plan for Tripura Board Class 12 Computer Science. Free to start, no card needed.