Lab 14
Lab 14
Laboratory 14
Version: 1.0.0
Contents:
• Learning Objectives
• Required Resources
• General Instructions
• Background and Overview
o Files and Streams
o Random-Access Files
o Exception
o Exception Handling
• Activities
o Pre-Lab Activity
▪ File Position Pointers
▪ Task 01
o In-Lab Activity
▪ Creating a Random-Access File
▪ Writing data to a Random File
▪ Reading data from a Random File
▪ Exception Handling
– C++ try
– C++ catch
– C++ throw
▪ Standard Exceptions
▪ User Defined Exceptions
▪ Rethrowing an Exception
▪ Constructor Destructor and Exception Handling
▪ Task 01
▪ Task 02
▪ Task 03
o Post-Lab Activity
▪ Task 01
• Submissions
• Evaluations Metric
• References and Additional Material
• Lab Time and Activity Simulation Log
Learning Objectives:
• Random-Access File
• Create Random-Access File
• Write to a Random-Access File
• Read from a Random-Access File
• Defining an Exception Class
• Rethrowing an Exception
• Constructor, Destructor and Exception handling
Resources Required:
• Desktop Computer or Laptop
• Microsoft ® Visual Studio 2022
General Instructions:
• In this Lab, you are NOT allowed to discuss your solution with your colleagues, even not
allowed to ask how is s/he doing, this may result in negative marking. You can ONLY discuss
with your Teaching Assistants (TAs) or Lab Instructor.
• Your TAs will be available in the Lab for your help. Alternatively, you can send your queries
via email to one of the followings.
Teachers:
Course Instructor Prof. Dr. Syed Waqar ul Qounain [email protected]
Lab Instructor Azka Saddiqa [email protected]
Activities:
Pre-Lab Activities:
File Position Pointers:
<istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte
number of the next byte in the file to be read or to be written). These member functions are:
The same operations can be performed with <ostream> function member seekp.
Example:
In this example, we open a file named “example.txt” for writing using std::ofstream. We then write
some data to the file using the << operator. We use the tellp() function to get the current position of the
file pointer and use seekp() to move the file pointer back to the beginning of the file. We then write
some more data to the file and use seekp() again to move the file pointer to the end of the file. Finally,
we write some more data to the file and close it.
File Content:
• Reads in a text file called “data.txt” containing records(objects) of the class “Record” with data
members:
o Id (int)
o Name (string)
o Balance (double)
• The program should then allow the user to search for a record by ID and update the balance for
that record
• Use seekg() and seekp() functions to move the read and write positions to the correct locations in
the file
In-Lab Activities:
Creating a Random-Access File:
Instant access is possible with random access files. Individual records of a random-access file can be
accessed directly without searching many other records.
Example:
we can say that the try block is used to define the block of code that needs to be tested for errors while
it is being executed.
E.g., Suppose we are dealing with databases, we should put the code that is handling the database
connection inside a try block as the database connection may raise some exceptions or errors.
C++ catch:
The catch block is used to catch and handle the error(s) thrown from the try block. If there are multiple
exceptions thrown from the try block, then we can use multiple catch blocks after the try blocks for
each exception. In this way, we can perform different actions for the various occurring exceptions. In
simple terms, we can say that the catch block is used to define a block of code to be executed if an error
occurs in the try block.
E.g., Let us take the same above example that we are dealing with the database. Now, if during the
connection, there is an exception raised inside the try block, then there should be a catch block present
to catch or accept the exception and handle the exception. The catch block ensures that the normal flow
of the code is not halted.
C++ throw:
The throw block is used to throw exceptions to the exception handler which further communicates the
error. The type of exception thrown should be same in the catch block. The throw keyword accepts one
parameter which is passed to the exception handler. We can throw both pre-defined as well as custom
exception(s) as per the requirements.
Whenever we want to explicitly throw an exception, we use the throw keyword. The throw keyword is
also used to generate the custom exception.
Following example demonstrates the overall working and syntax of try, catch, and throw in exception
handling.
Example:
Example:
Exception Description
exception This is an exception and the parent class of all standard C++ exceptions.
bad_alloc This exception is thrown by a new keyword.
bad_cast This is an exception thrown by dynamic_cast.
bad_exception A useful device for handling unexpected exceptions in C++ programs.
bad_typeid An exception thrown by typeid.
logic_error This exception is theoretically detectable by reading code.
domain_error This is an exception thrown after using a mathematically invalid domain.
invalid_argument An exception thrown for using invalid arguments.
length_error An exception thrown after creating a big std::string.
out_of_range Thrown by at method.
runtime_error This is an exception that cannot be detected via reading the code.
overflow_error This exception is thrown after the occurrence of a mathematical overflow.
range_error This exception is thrown when you attempt to store an out-of-range value.
underflow_error An exception thrown after the occurrence of mathematical underflow.
Example:
throw;
The above statement does not contain any arguments. This statement throws the exception to next try
catch block.
Example:
Example:
• Write a program that implements a database of employee records using a random-access file
called “employees.dat”.
• Each record in the file should contain the following fields:
class Employee {
int id;
char name[50];
char department[50];
float salary;
int numSubordinates;
int* subordinateIds; // dynamically allocated array of length numSubordinates
};
• The subordinateIds array stores the IDs of each employee's subordinates, with the length of the
array specified by the numSubordinates field.
• The program should allow the user to perform the following operations:
o Add a new employee record to the file at the end.
o Delete an employee record from the file based on their ID.
o Update the fields of an employee record in the file based on their ID.
o Print the information of an employee record in the file based on their ID.
o Print the information of all employee records in the file, sorted by salary in ascending order.
Task 02: Shopping Cart [Estimated time 40 minutes / 30 marks]
• Write a program that simulates a simple shopping cart system. The program consists of an Item
class with data members:
o Name
o Price
o Total quantity
• The program should allow the user to:
o Add items to their cart
o Remove items from their cart
o View the contents of their cart
o Calculate the total cost of the items in their cart
• The program should handle any errors that may occur during input or calculation, such as:
o Invalid input
o Out-of-stock items
o Insufficient funds.
Task 03: Sort Names [Estimated time 30 minutes / 20 marks]
• Create a program that reads in a list of names from a file and sorts them alphabetically.
• If any of the names in the file contain a non-alphabetic character, the program should throw a
custom exception called “InvalidNameException”.
• To accomplish this task, you'll need to create a “FileReader” class that reads the contents of the
file. Inside the FileReader class, you should define a member function called “readNames” that
takes the file name as a parameter and reads the names from the file one by one. If any of the
names contain a non-alphabetic character, the FileReader class should throw the
InvalidNameException.
• Next, you'll need to create a “NameSorter” class that takes the list of names as a parameter and
sorts them alphabetically. If any of the name length is greater than 15, the NameSorter class
should throw the custom InvalidLength exception.
Post-Lab Activities:
Task 01: Inventory Management [Estimated time 60 minutes / 50 marks]
• Create a program that simulates a simple inventory management system. The program should be
able to read in a list of items and their corresponding quantity from a file, allow the user to add or
remove items from the inventory, and output the updated inventory to a new file.
• The detailed description of the requirements are:
o The program should read in the inventory information from a file. Each line of the file should
contain the following information:
▪ Item name (string)
▪ Item quantity (integer)
o The program should then display the inventory information to the user, along with options to
add or remove items from the inventory.
o If the user chooses to add an item to the inventory, they should be prompted to enter the item
name and quantity. The program should then update the inventory accordingly.
o If the user chooses to remove an item from the inventory, they should be prompted to enter
the item name. The program should then update the inventory accordingly, but only if there
are enough items in the inventory to remove.
o If the user enters an invalid item name, the program should throw a custom exception that
informs the user of the error and prompts them to try again.
o After each modification to the inventory, the program should write the updated inventory
information to a new file using random-access file handling.
o The program should continue to display the updated inventory and prompt the user for actions
until the user chooses to exit the program.
Submissions:
• For In-Lab Activity:
▪ Save the files on your PC.
▪ TA’s will evaluate the tasks offline.
• For Pre-Lab & Post-Lab Activity:
▪ Submit the .cpp file on Google Classroom and name it to your roll no.
Evaluations Metric:
• All the lab tasks will be evaluated offline by TA’s
• Division of Pre-Lab marks: [20 marks]
▪ Task 01: Read Records [20 marks]
• Division of In-Lab marks: [80 marks]
▪ Task 01: Employee Database [30 marks]
▪ Task 02: Shopping Cart [30 marks]
▪ Task 03: Sort Names [20 marks]
• Division of Post-Lab marks: [50 marks]
▪ Task 01: Inventory Management [50 marks]