File Processing And Exceptional Handling (Copy)
Overview of File Processing
- File processing is essential for storing and retrieving structured data in programs.
- Files store records that contain multiple data types beyond just strings.
- Random access files allow retrieving records without reading the entire file sequentially.
Types of File Access
- Read Mode
- Opens a file for reading only.
- Data can be accessed but not modified.
- Write Mode
- Opens a file for writing.
- Overwrites existing content.
- Append Mode
- Opens a file to add data at the end without modifying existing content.
- Open Mode
- Prepares a file for access within a program.
- Close Mode
- Closes a file after use to free system resources.
Storing Records in Files
- A record structure is used to store related data elements together.
- Example Pseudocode for storing a student record:
TYPE TstudentRecord DECLARE name : STRING DECLARE registerNumber : INTEGER DECLARE dateOfBirth : DATE DECLARE fullTime : BOOLEAN ENDTYPE
Sequential and Serial File Storage
- Serial Files: Unordered file storage where records are appended.
- Sequential Files: Ordered file storage based on a key field.
- Algorithm for Storing a Record Sequentially:
DECLARE studentRecord : ARRAY[1:50] OF TstudentRecord DECLARE studentFile : STRING DECLARE counter : INTEGER counter ← 1 studentFile ← "studentFile.dat" OPEN studentFile FOR WRITE REPEAT INPUT student details PUTRECORD, studentRecord[counter] counter ← counter + 1 UNTIL no more records CLOSEFILE(studentFile)
Retrieving a Record from a Sequential File
- File is opened in READ mode.
- The program scans records sequentially to find the matching key.
- Example Pseudocode:
OPEN studentFile FOR READ WHILE NOT EOF(studentFile) GETRECORD studentFile, studentRecord OUTPUT studentRecord ENDWHILE CLOSEFILE(studentFile)
Appending a Record to a Sequential File
- Files are opened in APPEND mode.
- The new record is directly written to the end of the file.
- Example Code in Python:
with open("studentFile.dat", "a") as file: file.write("John, 1001, 2000-05-12, Truen")
Adding a Record to a Random File
- Uses hashing functions to determine the location of records.
- SEEK operation finds the correct address.
- Example Pseudocode:
DECLARE address : INTEGER address ← hash(studentRecord.registerNumber) SEEK studentFile, address PUTRECORD studentFile, studentRecord CLOSEFILE(studentFile)
20.2.2 Exception Handling
Understanding Exceptions
- Definition: An exception is an unexpected event that disrupts program execution.
- Common Causes of Exceptions:
- Division by zero.
- Reaching the end of a file unexpectedly.
- Attempting to open a non-existent file.
- Loss of connection to an external device.
Types of Errors Leading to Exceptions
- Programming Errors
- Logic mistakes or incorrect syntax.
- User Errors
- Invalid input that the program does not expect.
- Hardware Failures
- Disk failures, memory corruption, or loss of network connectivity.
Structure of Exception Handling
- TRY-EXCEPT-ENDTRY construct is used.
- Example Pseudocode:
TRY <statements> EXCEPT <error handling statements> ENDTRY
Exception Handling in Different Languages
- Python Example:
def division(a, b): try: result = a // b print("Result:", result) except: print("Error: Division by zero") division(10, 2) division(5, 0) - Java Example:
public class Division { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } } } - VB.NET Example:
Try Dim result As Integer = 10 0 Catch e As DivideByZeroException Console.WriteLine("Error: Division by zero") End Try
Handling File-Related Exceptions
- Common file-related exceptions include:
- File Not Found
- Permission Denied
- End of File (EOF) Reached
- Example of Handling a Missing File in Python:
try: file = open("non_existent_file.txt", "r") except FileNotFoundError: print("Error: The file does not exist.")
Using Finally Block for Cleanup
- Finally block executes regardless of whether an exception occurs.
- Ensures that resources like file handles are closed.
- Example:
try: file = open("data.txt", "r") content = file.read() except FileNotFoundError: print("File not found") finally: file.close()
Best Practices for Exception Handling
- Use Specific Exceptions
- Avoid general except statements.
- Provide Meaningful Error Messages
- Helps users understand what went wrong.
- Ensure Program Stability
- Prevent crashes by handling exceptions properly.
- Use Finally Blocks
- Ensures resources are freed.
- Log Errors for Debugging
- Maintain error logs to track issues.
Conclusion
- File processing allows programs to store and retrieve structured data efficiently.
- Exception handling enhances program robustness by preventing unexpected crashes.
- Best practices in handling files and exceptions lead to efficient and reliable programs.
