0% found this document useful (0 votes)
127 views5 pages

Class 12 Python Exception Handling Notes

The document provides notes on Python modules and exception handling for Class 12. It explains what modules are, how to create and import them, and details various types of exceptions along with their handling using try-except blocks. Additionally, it includes practical examples and practice questions to reinforce the concepts.

Uploaded by

Aniket Dubey
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)
127 views5 pages

Class 12 Python Exception Handling Notes

The document provides notes on Python modules and exception handling for Class 12. It explains what modules are, how to create and import them, and details various types of exceptions along with their handling using try-except blocks. Additionally, it includes practical examples and practice questions to reinforce the concepts.

Uploaded by

Aniket Dubey
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

Class 12 Python Notes

Topic 1: Modules in Python

Topic 2: Exception Handling (try-except block)

Topic 1: Modules in Python

✅ What is a Module?

A module is a file containing Python definitions and statements (functions, variables, or


classes) which can be reused in other programs.
It helps in code reusability, maintainability, and organization.

Types of Modules:

Type Example
Built-in Modules math, random, datetime, os, etc.
User-defined Modules Created by the programmer

Importing Modules

1. import module_name

import math
print([Link](25)) # Output: 5.0

2. import module_name as alias

import math as m
print([Link](5)) # Output: 120

3. from module_name import function_name

from math import pow


print(pow(2, 3)) # Output: 8.0

4. from module_name import *

from math import *


print(sin(90)) # Uses [Link]

Creating a User-defined Module

File: [Link]

def welcome(name):
print("Welcome", name)

File: [Link]

import greet
[Link]("Farhat")
✅ Advantages of Using Modules

• Code reuse
• Better code organization
• Easy to maintain and debug
• Collaboration in large projects

Topic 2: Exception Handling using try-except


✅ What is an Exception?

An exception is an error that occurs during the execution of a program.


Examples: divide by zero, invalid input, file not found, etc.

Common Python Exceptions

Exception Type Cause


ZeroDivisionError Division by zero
ValueError Invalid value (e.g., converting "abc" to int)
TypeError Invalid operation on data types
FileNotFoundError File not found
IndexError Index out of range in a list
KeyError Invalid key access in a dictionary

Syntax of try-except
try:
# Code that might cause error
except ExceptionType:
# Code to handle the error

✅ Example 1: Divide by Zero


try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")

✅ Example 2: Handling Multiple Exceptions


try:
num = int(input("Enter a number: "))
print("Reciprocal:", 1/num)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")

Using else and finally


try:
num = int(input("Enter a number: "))
print("Square:", num * num)
except ValueError:
print("Invalid number!")
else:
print("Operation successful.")
finally:
print("This block is always executed.")

✅ Summary of Keywords:

Keyword Purpose
try Block of code to monitor for errors
except Block that handles the error
else Executes if no exception occurred
finally Always executes, whether exception occurred or not

Real-life Example: File Handling with Exception


try:
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
except FileNotFoundError:
print("File not found!")

✅ Practice Questions:
1. Write a module that contains a function to find the factorial of a number. Import and
use it in another file.
2. Write a program that handles ValueError if the user enters a non-numeric input.
3. Create a program that opens a file and handles the FileNotFoundError if it doesn't
exist.

Part A: Modules – Questions with Answers


✅ Q1. Create a user-defined module [Link] with functions for
addition and subtraction. Import and use them in another file.

File: [Link]

def add(a, b):


return a + b

def subtract(a, b):


return a - b

File: [Link]

import calculator

x = 10
y = 5
print("Addition:", [Link](x, y))
print("Subtraction:", [Link](x, y))
✅ Q2. Write a Python program to import the math module and calculate the
area of a circle.
import math

radius = float(input("Enter the radius of the circle: "))


area = [Link] * radius ** 2
print("Area of circle =", area)

✅ Q3. Create a module [Link] with a function hello() that prints a


welcome message. Import and call it in another file.

[Link]

def hello():
print("Welcome to Class 12 Computer Science!")

[Link]

import greet
[Link]()

Part B: Exception Handling – Questions with Answers


✅ Q4. Write a program that takes two numbers and divides them. Handle
ZeroDivisionError.

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")

✅ Q5. Write a program that takes input and converts it to an integer.


Handle ValueError if the input is not a number.
try:
num = int(input("Enter a number: "))
print("Square:", num ** 2)
except ValueError:
print("Invalid input! Please enter a valid number.")

✅ Q6. Write a program to open and read a file. Handle FileNotFoundError.


try:
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
except FileNotFoundError:
print("File not found. Please check the filename.")
✅ Q7. Write a program to perform division and handle both ValueError and
ZeroDivisionError.

try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Result:", a / b)
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("Denominator cannot be zero.")

✅ Q8. Demonstrate the use of finally block in exception handling.


try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found.")
finally:
print("This block is always executed.")

✅ Q9. Write a function to calculate square root of a number using math


module and handle error if a negative number is passed.
import math

try:
num = float(input("Enter a number: "))
if num < 0:
raise ValueError("Negative number not allowed for square root.")
print("Square root:", [Link](num))
except ValueError as e:
print("Error:", e)

✅ Q10. Write a program to add two numbers. Handle any unexpected


exception using a generic except block.
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
except Exception as e:
print("Something went wrong:", e)

Common questions

Powered by AI

Built-in modules are pre-installed with Python and provide ready-to-use functionality, such as math for mathematical functions, datetime for date and time operations, and os for interacting with the operating system . User-defined modules, on the other hand, are created by programmers to encapsulate functions, classes, and variables in a separate file which can be imported and reused in other programs. An example of a user-defined module is greet.py, which contains a function to display a welcome message that can be imported and used in another file .

The try-except-else-finally structure in Python is used to manage exceptions efficiently. The 'try' block contains code that may cause exceptions during execution . If an exception occurs, it is caught by the corresponding 'except' block which provides code to handle the specific error . The 'else' block is executed if no exceptions are raised, allowing for the execution of code that depends on the success of the try block . The 'finally' block is always executed, regardless of whether an exception occurred or not, making it ideal for cleanup tasks such as closing files . This structure is crucial as it provides comprehensive error handling and ensures that critical parts of the code are executed, improving the robustness of the program .

Using exception handling to manage user inputs is highly practical for creating a robust user interface experience. It allows programs to manage invalid inputs gracefully, providing users with feedback and the opportunity to correct their inputs without crashing the program . For example, wrapping input conversions in a try block can catch ValueError exceptions when non-numeric inputs are provided, prompting the user for correct input . This results in a more user-friendly experience by making applications more tolerant to errors and guiding users towards correct interactions. Exception handling further allows for specific error messages that enhance user understanding and satisfaction, thus promoting a seamless and engaging user interface .

Creating user-defined modules in Python can significantly enhance teamwork in software development projects by promoting modular design. It allows team members to develop, test, and maintain specific functionalities independently, reducing conflicts and dependencies . Modules enable clear separation of concerns; each team member can focus on a specific module or component, enhancing productivity and reducing integration issues. This modular approach also facilitates easy collaboration, as team members can work on different modules concurrently and integrate them more smoothly into larger systems . Furthermore, well-documented modules improve understanding and communication within the team, ensuring everyone can leverage shared functionalities effectively in various parts of the project .

Python's handling of multiple exceptions within a single try-except block allows for specific management of different error types. It enables a program to catch and handle various exceptions that may arise from a single block of code, enhancing robustness and flexibility. For example, using multiple 'except' clauses allows a program to display contextual error messages for both ZeroDivisionError and ValueError when performing divisions, thus providing precise feedback for specific issues . This mechanism simplifies exception handling logic by reducing the need for deeply nested try-except constructs, leading to cleaner and more maintainable code .

The 'finally' block in Python's exception handling plays an essential role by executing its content regardless of whether an exception occurs or not . It ensures that cleanup operations, such as closing files or releasing resources, are performed consistently, which is critical for preventing resource leaks and maintaining application stability . Even if no exceptions are raised, the 'finally' block executes, making it a reliable place to put code that must run after the try-except sequence, thus ensuring that the program state is correctly finalized .

Modules in Python provide several benefits that enhance a project's functionality. They enable code reuse, which allows developers to write functions or classes once and use them across multiple programs, thereby reducing redundancy . Modules offer better code organization by dividing programs into separate files, making large projects more manageable and collaborative . They also simplify maintenance and debugging, as each module can be tested and verified independently . Built-in and user-defined modules enhance Python projects by offering ready-to-use functionalities, from mathematical operations to system interfacing .

Exception handling in Python improves program reliability by managing and recovering from errors gracefully. The use of try-except blocks allows the program to continue executing even when unexpected errors occur . For example, handling a ZeroDivisionError prevents the program from crashing when a division by zero is attempted, providing an error message instead . It enhances user experience by providing informative feedback when inputs are invalid, such as catching ValueError when a non-numeric input is provided . Furthermore, the use of else and finally blocks allows handling of successful operations and the execution of cleanup actions, ensuring the program runs smoothly .

Using specific exception types rather than a generic 'except Exception' block is considered good practice in Python because it provides clarity and control over error handling . Specific exceptions allow developers to create more informative and targeted error messages, improving the debugging process and user feedback . In contrast, catching exceptions generically can mask errors and prevent developers from understanding the root cause of issues, making debugging more challenging . The use of generic 'except Exception' can also inadvertently catch unexpected and non-critical exceptions, potentially leading to inappropriate handling steps or the suppression of important errors that should be addressed separately .

Import statements are crucial in Python for incorporating modules and their functionalities into a program, promoting code reuse and modular design. Different import styles affect code usage and readability significantly. Using 'import module_name' makes all objects from the module accessible by prefixing with the module name, which enhances code readability by showing the object's origin . 'import module_name as alias' provides a shorthand for frequently used modules, improving readability without verbosity . 'from module_name import function_name' allows direct access to specific functions or classes without module prefixing, which can make code cleaner but less explicit in indicating where functions originate . Finally, 'from module_name import *' imports all objects into the local namespace, which can lead to namespace pollution and make code less readable by hiding dependencies and origins .

You might also like