Unit 3: File Handling and Exception Handling - Subjective Questions
CAP776 — Programming In Python • Practice Questions with Detailed Answers
20 questions
What is an exception in Python? Explain the difference between a syntax error, a runtime error, and an exception with suitable examples.
An exception is an event that occurs during program execution and disrupts the normal flow of instructions. Python provides mechanisms to detect and handle such events.
- Syntax error: Occurs when the Python interpreter cannot understand the structure of a program. It is detected before execution.
- Example:
if x > 5 print(x)
- Example:
- Runtime error: Occurs while the program is running, often because of invalid operations or unavailable resources.
- Example: Attempting to divide by zero.
- Exception: A runtime error represented as an object that can be caught and handled by the program.
- Example:
10 / 0raisesZeroDivisionError.
- Example:
Exception handling allows a program to respond gracefully instead of terminating unexpectedly.
Explain the purpose and syntax of the try and except statements in Python. Illustrate your answer with a suitable program.
The try statement contains code that may produce an exception, while the except block contains code that handles the exception.
General syntax:
try:
risky code
except ExceptionType:
handling code
Example:
try:
a = int(input("Enter a number: "))
result = 100 / a
print(result)
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("The number cannot be zero.")
The program continues in a controlled manner when an expected exception occurs. Specific exception types should generally be handled instead of using an unrestricted except block.
Describe any five built-in exceptions in Python and explain the situations in which each exception is raised.
Python provides many built-in exceptions for common programming errors. Five important examples are:
ValueError: Raised when a function receives a value of the correct type but an inappropriate format, such asint("abc").TypeError: Raised when an operation is applied to an inappropriate data type, such as adding a string and an integer.ZeroDivisionError: Raised when a number is divided by zero.IndexError: Raised when an invalid sequence index is accessed.KeyError: Raised when a nonexistent key is requested from a dictionary.
Other examples include FileNotFoundError, NameError, AttributeError, and ImportError. Recognizing built-in exceptions helps programmers write precise exception-handling code.
Explain how multiple except blocks are used in Python. Why is it preferable to catch specific exceptions?
Multiple except blocks allow a program to handle different exceptions in different ways.
Example:
try:
number = int(input("Enter a number: "))
answer = 50 / number
except ValueError:
print("Input must be an integer.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
Specific exception handling is preferable because:
- It identifies the exact cause of failure.
- It provides an appropriate message or recovery action.
- It prevents unrelated programming errors from being hidden.
- It improves code readability and debugging.
A broad except Exception: block may be used when several unexpected exceptions need common handling, but a bare except: should be avoided unless there is a clear reason.
Explain the use of the else and finally clauses with exception handling. Include a program demonstrating both clauses.
The else and finally clauses provide additional control in exception handling.
else: Executes only when thetryblock completes without raising an exception.finally: Executes regardless of whether an exception occurs. It is commonly used for cleanup operations such as closing files.
Example:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File does not exist.")
else:
print("File opened successfully.")
print(file.read())
finally:
print("File-processing operation completed.")
The finally block is useful because cleanup code runs even if an exception interrupts normal execution.
What is the purpose of the raise statement in Python? Explain how it can be used to generate a built-in exception.
The raise statement is used to explicitly generate an exception when a program detects an invalid condition.
Example:
age = int(input("Enter age: "))
if age < 0:
raise ValueError("Age cannot be negative")
print("Valid age")
In this example, the programmer raises ValueError because a negative age is logically invalid. The exception can be handled by an enclosing try and except statement.
The general form is:
raise ExceptionType("error message")
Using raise allows programmers to enforce rules and report errors clearly rather than allowing invalid data to continue through the program.
Define a user-defined exception. Explain the steps for creating and using one in Python with an example.
A user-defined exception is a custom exception created by a programmer to represent an application-specific error. It is generally defined by creating a class that inherits from Exception or one of its subclasses.
Example:
class InsufficientBalanceError(Exception):
pass
balance = 500
withdrawal = 800
try:
if withdrawal > balance:
raise InsufficientBalanceError("Insufficient balance")
balance -= withdrawal
except InsufficientBalanceError as error:
print(error)
The steps are:
- Define a class derived from
Exception. - Detect the application-specific invalid condition.
- Raise the custom exception using
raise. - Catch and handle it with
except.
Compare built-in exceptions and user-defined exceptions in Python.
Built-in and user-defined exceptions both represent errors, but they differ in origin and purpose.
| Feature | Built-in exceptions | User-defined exceptions |
|---|---|---|
| Definition | Provided by Python | Created by the programmer |
| Purpose | Handle common language and system errors | Represent application-specific conditions |
| Examples | ValueError, TypeError, FileNotFoundError |
InvalidMarksError, InsufficientBalanceError |
| Creation | No class definition is normally required | A class is usually derived from Exception |
| Usage | Used for standard runtime problems | Used to make domain-specific errors clearer |
For example, ValueError is suitable for invalid conversion, whereas a custom InvalidAgeError may more clearly communicate a rule specific to an application. Both can be raised, caught, and handled using the same exception-handling mechanism.
Explain text file handling in Python. Describe the important file modes and the purpose of the open() function.
Text file handling involves opening a file, performing read or write operations, and closing the file after use. Python uses the open() function for this purpose.
Syntax:
file_object = open(filename, mode)
Important modes include:
r: Opens a file for reading. It raisesFileNotFoundErrorif the file does not exist.w: Opens a file for writing and replaces existing contents. It creates the file if necessary.a: Opens a file for appending data at the end.x: Creates a new file and raises an error if it already exists.r+: Opens a file for both reading and writing.
Text mode is the default. A file should be closed after use, preferably by using a with statement, which closes it automatically.
Explain different methods for reading text files in Python, namely read(), readline(), and readlines().
Python provides several methods for reading text files:
read(): Reads the complete file, or a specified number of characters if a size argument is supplied.- Example:
content = file.read()
- Example:
readline(): Reads one line at a time and retains the newline character when present.- Example:
line = file.readline()
- Example:
readlines(): Reads all lines and returns them as a list of strings.- Example:
lines = file.readlines()
- Example:
A file can also be read efficiently line by line using:
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
The iteration approach is generally preferable for large files because it does not load the entire file into memory at once.
Explain the different ways of writing text to a file in Python using write() and writelines().
Python provides write() and writelines() for writing text files.
write(): Writes a single string to a file. It does not automatically add a newline.writelines(): Writes a sequence of strings. It also does not automatically insert newline characters.
Example:
with open("notes.txt", "w") as file:
file.write("Python file handling\n")
file.write("Exception handling\n")
Using writelines():
lines = ["First line\n", "Second line\n"]
with open("notes.txt", "w") as file:
file.writelines(lines)
The newline character must be included explicitly when separate lines are required. Using mode w replaces existing contents, while mode a preserves them and adds new content at the end.
Why is the with open() statement recommended for file handling? Explain its advantages over explicitly calling close().
The with open() statement creates a context manager for file operations.
Example:
with open("report.txt", "r") as file:
data = file.read()
After the indented block finishes, Python automatically closes the file.
Advantages include:
- Automatic closure: The file is closed when the block ends.
- Exception safety: The file is closed even if an exception occurs inside the block.
- Reduced code: There is no need to write
file.close()separately. - Better resource management: Operating-system resources are released promptly.
- Improved readability: The lifetime of the file object is clear from the code structure.
Although close() can be used explicitly, forgetting to call it may cause resource leaks or incomplete writes. Therefore, context managers are the preferred approach.
Write and explain a Python program that copies the contents of one text file into another while handling possible file-related exceptions.
A file-copying program should handle errors such as a missing source file and permission problems.
Program:
try:
with open("source.txt", "r") as source:
content = source.read()
with open("backup.txt", "w") as destination:
destination.write(content)
print("File copied successfully.")
except FileNotFoundError:
print("The source file was not found.")
except PermissionError:
print("Permission denied while accessing a file.")
except OSError as error:
print("File operation failed:", error)
The with statements ensure that both files are closed automatically. Specific exceptions provide meaningful responses, while OSError handles other operating-system-level file errors.
Explain how to handle FileNotFoundError, PermissionError, and OSError while working with text files.
File operations may fail for several reasons, and Python provides exceptions for handling them.
FileNotFoundError: Raised when a requested file or directory does not exist.PermissionError: Raised when the program lacks permission to read, write, or access a file.OSError: A broader exception for operating-system-related errors. It can serve as a common parent for several file-system exceptions.
Example:
try:
with open("input.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Check whether the file name and path are correct.")
except PermissionError:
print("You do not have permission to read this file.")
except OSError as error:
print("An operating-system error occurred:", error)
Specific exceptions should be placed before broader exceptions such as OSError.
What is JSON? Explain the relationship between common JSON data types and their corresponding Python data types.
JSON, or JavaScript Object Notation, is a lightweight text format used to store and exchange structured data. It is commonly used in configuration files, web applications, and data-interchange systems.
| JSON type | Python type |
|---|---|
| Object | Dictionary (dict) |
| Array | List (list) |
| String | String (str) |
| Number | Integer (int) or floating-point number (float) |
true or false |
True or False |
null |
None |
A JSON object uses key-value pairs, and keys must be enclosed in double quotes. JSON is language-independent, while Python provides the built-in json module to encode and decode JSON data.
Explain how to read a JSON file in Python using the json module. Include a suitable program and describe the result.
A JSON file can be read using the json.load() function. The function reads JSON text from a file and converts it into an equivalent Python object.
Example JSON file, student.json:
{"name": "Asha", "marks": 85, "subjects": ["Python", "Math"]}
Python program:
import json
with open("student.json", "r") as file:
student = json.load(file)
print(student["name"])
print(student["marks"])
print(student["subjects"])
The JSON object is converted into a Python dictionary. Its array becomes a list, its strings remain strings, and its number becomes an integer. The with statement ensures that the file is closed automatically.
Differentiate between json.load() and json.loads() in Python with examples.
Both functions convert JSON data into Python objects, but their inputs are different.
json.load()reads JSON data from an already opened file object.- Example:
data = json.load(file)
- Example:
json.loads()reads JSON data from a Python string. The finalsmeans string.- Example:
data = json.loads('{"city": "Delhi"}')
- Example:
Example using json.load():
import json
with open("config.json", "r") as file:
config = json.load(file)
Example using json.loads():
text = '{"city": "Delhi"}'
config = json.loads(text)
Thus, load() is used for file input, whereas loads() is used for JSON text already stored in memory.
Explain the exceptions that may occur while reading JSON files and describe how they can be handled.
Several exceptions may occur during JSON file processing:
FileNotFoundError: The specified JSON file does not exist.PermissionError: The program cannot access the file because of insufficient permissions.json.JSONDecodeError: The file contains invalid JSON syntax.UnicodeDecodeError: The file encoding cannot be decoded using the selected encoding.OSError: A general operating-system-related file error occurs.
Example:
import json
try:
with open("settings.json", "r", encoding="utf-8") as file:
settings = json.load(file)
except FileNotFoundError:
print("JSON file not found.")
except json.JSONDecodeError:
print("The JSON content is invalid.")
except PermissionError:
print("Permission denied.")
except OSError as error:
print("File error:", error)
Handling these exceptions prevents malformed or inaccessible files from crashing the program unexpectedly.
Write a Python program that reads a JSON file containing student records and calculates the average marks. Include suitable exception handling.
Assume students.json contains an array of objects such as:
[{"name": "Asha", "marks": 80}, {"name": "Ravi", "marks": 90}]
Program:
import json
try:
with open("students.json", "r", encoding="utf-8") as file:
students = json.load(file)
if not students:
raise ValueError("The student list is empty.")
total = sum(student["marks"] for student in students)
average = total / len(students)
print("Average marks:", average)
except FileNotFoundError:
print("Student file was not found.")
except json.JSONDecodeError:
print("Invalid JSON format.")
except KeyError:
print("A record does not contain the marks field.")
except (TypeError, ValueError, ZeroDivisionError) as error:
print("Invalid student data:", error)
The program loads the JSON array, extracts marks, calculates the average, and handles file, format, and data-related errors.
Explain the difference between handling an exception and suppressing an exception. Why should exceptions not be silently ignored?
Handling an exception means responding to an error in a meaningful way, such as displaying a message, recording the problem, using a default value, or retrying the operation. Suppressing an exception means ignoring it without informing the user or taking corrective action.
Meaningful handling:
try:
value = int(text)
except ValueError:
print("Please provide a valid integer.")
Silently ignoring errors can be dangerous because:
- It hides bugs and makes debugging difficult.
- It may produce incorrect results.
- It can leave files or other resources in an unsafe state.
- Users may not know that an operation failed.
- Later code may fail in a less understandable way.
Exceptions should be caught only when the program can handle them appropriately. Otherwise, they should be allowed to propagate or be logged for further investigation.
What is an exception in Python? Explain the difference between a syntax error, a runtime error, and an exception with suitable examples.
An exception is an event that occurs during program execution and disrupts the normal flow of instructions. Python provides mechanisms to detect and handle such events.
- Syntax error: Occurs when the Python interpreter cannot understand the structure of a program. It is detected before execution.
- Example:
if x > 5 print(x)
- Example:
- Runtime error: Occurs while the program is running, often because of invalid operations or unavailable resources.
- Example: Attempting to divide by zero.
- Exception: A runtime error represented as an object that can be caught and handled by the program.
- Example:
10 / 0raisesZeroDivisionError.
- Example:
Exception handling allows a program to respond gracefully instead of terminating unexpectedly.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →