ALevel-CS Chapter 26 File processing and exception handling

26.01 Records

Records

pseudocode

TYPE CarRecord 
    DECLARE VehicleID : STRING
    DECLARE Registration  : STRING
    DECLARE DateOfRegistration : DATE
    DECLARE EngineSize : INTEGER
    DECLARE PurchasePrice  : CURRENC
ENDTYPE

// declare a variable

DECLARE ThisCar : CarRecord

python code

class CarRecord: # declaring a class without other methods 
    def __init__(self): # constructor 
        self.VehicleID = "" 
        self.Registration = "" 
        self.DateOfRegistration = None 
        self.EngineSize = 0 
        self.PurchasePrice = 0.00 
ThisCar = CarRecord() # instantiates a car record 
ThisCar.EngineSize = 2500 # assign a value to a field 
Car = [CarRecord() for i in range(100)] # make a list of 100 car records 
Car[1].EngineSize = 2500 # assign value to a field of the 2nd car in list

Java code

class CarRecord {
    String vehicleID; 
    String registration; 
    String dateOfRegistration; 
    int engineSize; 
    double purchasePrice;

    public CarRecord() { // declare a constructor without other methods
        vehicleID = "XX";
        registration = ""; 
        dateOfRegistration = "01/01/2010"; 
        engineSize = 0; 
        purchasePrice = 0.00;
    }
}

CarRecord thisCar = new CarRecord(); // instantiates a car record 
thisCar.engineSize = 2500; // assign a value to a field

CarRecord[] car = new CarRecord[100]; // declare an array of car record type

car[2] = new CarRecord(); // instantiate a car 
car[2].engineSize = 2500; // assign a value to a field of 2nd car in array

26.02 File processing

Key Terms

File processing

Structured English Pseudocode
Create a file and open it for writing OPENFILE FOR WRITE
Open a file in append mode OPENFILE FOR APPEND
Open a file for reading OPENFILE FOR READ
Open a file for random access OPENFILE FOR RANDOM
Close a file CLOSEFILE
Write a record to a file PUTRECORD ,
Read a record from a file GETRECORD ,
Move to a specific disk address within the file SEEK ,
Test for end of file EOF()

Sequential file processing

// Saving content of array
OPENFILE CarFile FOR WRITE
FOR i ← 1 TO MaxRecords
    PUTRECORD CarFile, Car[i]
NEXT i
CLOSEFILE CarFile

// Restoring contents of array
OPENFILE CarFile FOR READ
FOR i ← 1 TO MaxRecords
    GETRECORD CarFile, Car[i]
NEXT i
CLOSEFILE CarFile
import pickle # this library is required to create binary files 
Car = [CarRecord() for i in range(100)]

CarFile = open('CarFile.DAT', 'wb') # open file for binary write

for i in range(100): # loop for each array element 
    pickle.dump(Car[i], CarFile) # write a whole record to the binary file

CarFile.close() # close file

CarFile = open('CarFile.DAT', 'rb') # open file for binary read

Car = [] # start with empty list 
while True: # check for end of file 
    Car.append(pickle.load(CarFile)) # append record from file to end of list

CarFile.close()
// writing records to a file:

import java.io.DataOutputStream; 
import java.io.FileOutputStream; 
import java.io.EOFException; 
import java.io.FileInputStream; 
import java.io.FileOutputStream;

try 
{ // set up file stream and link to file name 
    FileOutputStream fos = new FileOutputStream("CarFile.DAT"); 
    // link file stream to data stream 
    DataOutputStream dos = new DataOutputStream(fos); 
    for (int i = 1; i < 100; i++) // loop for each array element    
    { 
        dos.writeUTF(car[i].vehicleID); // write a field to the file        
        dos.writeUTF(car[i].registration); dos.writeInt(car[i].engineSize); 
        dos.writeUTF(car[i].dateOfRegistration); 
        dos.writeDouble(car[i].purchasePrice); 
    } 
    dos.close(); // close data stream
} 
catch (Exception x) 
{ 
    System.out.println("IO error"); 
}

// reading records back into array:

CarRecord[] car = new CarRecord[100]; 
try 
{ // set up file stream and link to file name
    FileInputStream fis = new FileInputStream("CarFile.DAT"); 
    // link file stream to data stream 
    DataInputStream dis = new DataInputStream(fis); 
    int i = 1; 
    while (true) // loop for each array element 
    {
        thisCar = new CarRecord(); 
        thisCar.vehicleID = dis.readUTF(); // read fields from the file 
        thisCar.registration = dis.readUTF(); 
        thisCar.engineSize = dis.readInt(); 
        thisCar.dateOfRegistration = dis.readUTF(); 
        thisCar.purchasePrice = dis.readDouble(); 
        car[i] = thisCar; // assign record to next array element 
        i += 1;
    }
} 
catch (EOFException x) 
{
    System.out.println("End of File reached"); 
} 
catch (Exception x) 
{
    System.out.println(x); // output error message 
}

Random-access file processing

pseudocode

// Saving a record
OPENFILE CarFile FOR RANDOM
Address ← Hash(ThisCar.VehicleID)
SEEK CarFile, Address
PUTRECORD CarFile, ThisCar
CLOSEFILE CarFile

// Retrieving a record
OPENFILE CarFile FOR RANDOM
Address ← Hash(ThisCar.VehicleID)
SEEK CarFile, Address
GETRECORD CarFile, ThisCar
CLOSEFILE CarFile

python

import pickle # this library is required to create binary files 
ThisCar = CarRecord()

CarFile = open('CarFile.DAT','rb+') # open file for binary read and write
Address = hash(ThisCar.VehicleID) 
CarFile.seek(Address) 
pickle.dump(ThisCar, CarFile) # write a whole record to the binary file 
CarFile.close() # close file



// to find a record from a given VehicleID:

CarFile = open('CarFile.DAT','rb')  # open file for binary read
Address = hash(VehicleID)
CarFile.seek(Address) 
ThisCar = pickle.load(CarFile) # load record from file 
CarFile.close()

java

CarRecord thisCar;
int recordSize = 50;
try // set up a file with 100 dummy records
{
    RandomAccessFile writer = new RandomAccessFile("CarFile.DAT", "rw"); 
    for (int i = 1; i < 100; i++) // loop for each array element
    {
        thisCar = new CarRecord();
        thisCar.vehicleID = "A" + i;
        writer.seek(i * recordSize);
        writer.writeUTF(thisCar.vehicleID);
        writer.writeUTF(thisCar.registration);
        writer.writeUTF(thisCar.dateOfRegistration);
        writer.writeInt(thisCar.engineSize);
        writer.writeDouble(thisCar.purchasePrice);
    }
    writer.close();
} catch (IOException x) 
{ 
}

//to find a record from a given VehicleID:

try {
    RandomAccessFile writer = new RandomAccessFile("CarFile.DAT", "rw"); 
    RandomAccessFile reader = new RandomAccessFile("CarFile.DAT", "r"); 
    reader.seek(hash(vehicleID)); 
    thisCar = new CarRecord(); 
    thisCar.vehicleID = reader.readUTF(); 
    thisCar.registration = reader.readUTF(); 
    thisCar.engineSize = reader.readInt(); 
    thisCar.dateOfRegistration = reader.readUTF(); 
    thisCar.purchasePrice = reader.readDouble(); 
    reader.close();

} 
catch (IOException x) 
{

}

26.03 Exception handling

Exception handling

Run-time errors can occur for many reasons. Some examples are division by zero, invalid array index or trying to open a non-existent file. Run-time errors are called ‘exceptions’. They can be handled (resolved) with an error subroutine (known as an ‘exception handler’), rather than let the program crash.

TRY
    <statementsA> 
EXCEPT
    <statementsB> 
ENDTRY

Any run-time error that occurs during the execution of <statementsA> is caught and handled by executing <statementsB>.

There can be more than one EXCEPT block, each handling a different type of exception.

Sometimes a FINALLY block follows the exception handler.

Python distinguishes between different types of exception, such as:

Java distinguishes between different types of exception, such as:

Example of exception handling

python

NumberString = input("Enter an integer: ") 
try:
    n = int(NumberString)
    print(n) 
except:
    print("This was not an integer")

java

import java.util.Scanner; 

{
    public static void main(String[] args) 
    { 
        Scanner console = new Scanner(System.in); 
        try 
        { 
            System.out.print("Enter an integer: "); 
            int n = console.nextInt(); 
            System.out.println(n); 
        } 
        catch(Exception e) // catches any exception 
        { 
            System.out.println("This was not an integer"); 
        }
    }
}